C#: List

.NET Array Collections File String Async Cast DataTable DateTime Dictionary Enum Exception For Foreach IEnumerable If IndexOf Lambda LINQ List Parse Path Process Property Regex Replace Sort Split StringBuilder Substring Switch Tuple


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.


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.

C# program that removes duplicates in List

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

class Program
    static void Main()
	// List with duplicate elements.
	List<int> list = new List<int>();

	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);


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


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.


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


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.