How to avoid duplicates items from Generic List in C#?

Posted by Naveenmanam under C# on 5/4/2010 | Views : 4109 | Status : [Member] | Replies : 1
Hi,

I have a generic List (i.e. List<Subjects>). Which can contain list of categories and their subjects. But i need to retrieve only unique category names and their list of subjects. Usually, it returns like this...

Cat1 Sub1

Cat1 Sub2

Cat2 Sub3

Cat2 Sub4

I don't need like this. The list should contain only...

Cat1 Sub1, Sub2

Cat2 Sub3, Sub4

NaveenKumar


Responses

Posted by: Er.deepakdalal on: 5/4/2010 [Member] Starter

Up
0
Down
Hi Naveenmanam

try Below Code it will remove the duplicates


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


Naveenmanam, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response