Friday 30 September 2011

Removing Duplicates from List

Although there are many different ways you can remove duplicate elements from aList 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. Here, we look at how you can remove duplicate elements from a List using the Distinct method.

Example

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.
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

No comments:

Post a Comment