Click here to Skip to main content
15,921,837 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I have a list where all items are string.

Like ab,bc,ab,ts,ab,bc,ts,op

From here you can see, there is a lot of string item in different places of list are same.

I want get all the items only for once from this list.

Like ab,bc,ts,op from from the given list.

how can i get different item all items from a list?
Posted

1 solution

You could use Distinct method of collection.
Distinct removes all duplicate elements in a collection. It returns only the distinct elements. The System.Linq namespace provides this extension method.
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);
	}
    }

Hope this would help you :)
-KR
 
Share this answer
 
Comments
Krunal Rohit 18-Feb-14 4:11am    
I forgot to mention output of this,
Before : 1, 1, 2, 2, 3, 3, 4, 4, 4
After : 1, 2, 3, 4

-KR
[no name] 18-Feb-14 5:12am    
so quick :)
Krunal Rohit 18-Feb-14 5:13am    
what is so quick ?
-KR
[no name] 18-Feb-14 5:14am    
I mean you are answering all the listed questions quickly :)

-PN
Krunal Rohit 18-Feb-14 5:15am    
This is me :) Thanks though..

-KR

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900