How to find unique elements in List.

Posted by Oswaldlily under C# on 11/24/2011 | Points: 10 | Views : 1927 | Status : [Member] | Replies : 3
How to find unique elements in List.

If i need to find unique values oly by passing into hashset,
how to pass list to hashset?




Responses

Posted by: Dnandha87 on: 11/24/2011 [Member] Starter | Points: 25

Up
0
Down
suppose ths is the list:

List<string> lst = new List<string>()
lst.add("a");
lst.add("b");
lst.add("c");
lst.add("d");

On what basis u wants to get the unique name?



Regards
Nandha Kumar,

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

Posted by: Oswaldlily on: 11/24/2011 [Member] Starter | Points: 25

Up
0
Down
in list it ll be as " a b a b a b"

unique elements " a b"

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

Posted by: Dnandha87 on: 11/24/2011 [Member] Starter | Points: 25

Up
0
Down
The following fn will solve ur problem...

public void FindUnique()
{
List<string> lstName = new List<string>();
lstName.Add("nandha");
lstName.Add("kumar");
lstName.Add("nandha");
lstName.Add("nandhu");
lstName.Add("kumar");
lstName.Add("nandhaa");

HashSet<string> hashName = new HashSet<string>();

foreach (string item in lstName)
{
if (!(hashName.Contains(item)))
{
hashName.Add(item);
}
}
}


Now the hashName contains
Nandha
kumar
Nandhu
Nandhaa

Regards
Nandha Kumar,

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

Login to post response