C# Remove Duplicates

List type

Programs sometimes must remove duplicate List elements. There are many ways to remove these elements. Some are easier to implement than others. One approach uses the Distinct extension method from System.Linq.

Example

First, this program requires a newer .NET Framework, because it uses the System.Linq namespace. In Main, a List with seven int elements is created. But the List contains duplicate elements for the values 3 and 4.

IntWarning: exclamation mark

Tip:By using the Distinct parameterless extension method on the List type, we can remove those duplicate elements.

Then:We can optionally invoke the ToList extension to get an actual List with the duplicates removed.

ToList
Program that removes duplicates in List: C#

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
	// List with duplicate elements.
	List<int> list = new List<int>();
	list.Add(1);
	list.Add(2);
	list.Add(3);
	list.Add(3);
	list.Add(4);
	list.Add(4);
	list.Add(4);

	foreach (int value in list)
	{
	    Console.WriteLine("Before: {0}", value);
	}

	// Get distinct elements and convert into a list again.
	List<int> distinct = list.Distinct().ToList();

	foreach (int value in distinct)
	{
	    Console.WriteLine("After: {0}", value);
	}
    }
}

Output

Before: 1
Before: 2
Before: 3
Before: 3
Before: 4
Before: 4
Before: 4
After: 1
After: 2
After: 3
After: 4

Distinct

LINQ: language integrated query

We review the Distinct extension method. Found in the System.Linq namespace, this method can also be invoked on other types of collections, such as arrays. It acts upon types that implement IEnumerable.

Distinct Extension MethodIEnumerable

Also:It can specify an equality comparer, which it uses to determine what elements are equal and can be made distinct.

Summary

The C# programming language

LINQ extension methods are useful on List collections. Developers often favor the List type over the array type for its resizable behavior. So the LINQ extension methods such as Distinct may be more commonly invoked on this type.

Tip:For erasing duplicate elements in a list and making every element unique, you can employ the Distinct extension method.


C#: Collections: List