Removing Duplicates from a List in C# - Page 1
       by kirupa  |  16 November 2006

When you are dealing with a list of data, you may be interested in filtering out all duplicate values. For example, let's say your input resembles the following:

   input = { there, here, deer, dear, there, pier, deer, leer }

Your output with duplicates removed would be:

   input = { there, here, near, deer, dear, pier leer }

The duplicate there's and deer's were removed. In this tutorial, I will provide the code for removing duplicates and then explain how the code actually works to efficiently remove duplicate elements.

The Code
The code for removing duplicate values is:

static List<string> removeDuplicates(List<string> inputList)
{
Dictionary<string, int> uniqueStore = new Dictionary<string, int>();
List<string> finalList = new List<string>();
 
foreach (string currValue in inputList)
{
if (!uniqueStore.ContainsKey(currValue))
{
uniqueStore.Add(currValue, 0);
finalList.Add(currValue);
}
}
return finalList;
}

Note that the above code is designed for Lists that store string data, but you can modify the code easily to accept any type of data! Don't worry - I will explain later.

How to Use the Code
To test the above code, all you need is a List that contains duplicate values. You can copy and paste the following main method to see for yourself:

static void Main(string[] args)
{
List<string> input = new List<string>();
input.Add("There");
input.Add("Here");
input.Add("Sneer");
input.Add("There");
input.Add("Near");
input.Add("Meer");
input.Add("Here");
 
List<string> result = removeDuplicates(input);
}

I am declaring a new List called input and adding some sample values. Some of the values are duplicates.

Next, I declare a new List called result that passes the input list into our removeDuplicates method. This works because our removeDuplicates method returns a new list. You can use a loop to print out the values in the result loop, but I will leave it up to you on how you choose to do that.

Onwards to the next page!

1 | 2 | 3




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.