
Although there are many different ways you can remove duplicate elements from a List collection in the C# language, some are easier to implement than others. One approach, which involves using the Distinct extension method, is the easiest to add but has less predictable performance.

First, this program requires a newer installation of the .NET Framework, because it uses the System.Linq namespace. In the Main method, a List with seven integer elements is created. However, the list contains duplicate elements for the values 3 and 4.
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.
This C# program removes duplicate elements from a List collection.
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
Do you want to know more about 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 can also specify an equality comparer, which it uses to determine what elements are equal and can be made distinct.
Distinct Extension MethodUsing the LINQ extension methods can be very useful when you have List collection. Because developers often favor the List type over the array type for its resizable behavior, the LINQ extension methods such as Distinct may be more commonly invoked on this type. For erasing duplicate elements in a list and making every element unique, you can employ the Distinct extension method.
Collections