How to Remove Duplicates from a List

Er.deepakdalal
Posted by Er.deepakdalal under C# category on | Views : 6341
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;
}

Comments or Responses

Posted by: Puneet20884 on: 5/12/2010 Level:Bronze | Status: [Member]
Hi Deepak,

It's a nice code snippet,
Better you also add some description of the Loginc and code along side, for a general user to understand better.


Posted by: Deeraj on: 6/8/2010 Level:Starter | Status: [Member]

using LINQ to objects its even simpler; No additional collections will need to be created!

List<string> MyList = new List<string>();

MyList.Add("A");
MyList.Add("A");
MyList.Add("B");
MyList.Add("A");
MyList.Add("E");
MyList.Add("A");
MyList.Add("E");
MyList.Add("C");
MyList.Add("D");

var MyQuery = (from item in MyList
orderby item
select item).Distinct() ;

foreach (string item in MyQuery)
{
Console.WriteLine(item);
}


The output of the above code is :
A
B
C
D
E

Hope that helps!

Login to post response