How to remove identical elements from the <string> list?

I have a list in which I select users from db every time the sql query is launched with a specific value and selects one user at a time, so I can not limit the same users in sql.

I have a list with:

list[0] = "jerry" list[1] = "tom" list[2] = "jerry" 

I want anyone (the first or the last doesn't matter in my case) to be removed from the list.

thanks

+4
source share
5 answers

LINQ can solve this problem:

 List<string> names = new List<string> { "Tom", "Jerry", "Tom" }; IQueryable<string> distinctItems = names.Distinct(); 

If you need a list type, just call ToList ():

 distinctItems.ToList(); 

Here is an example from MSDN .

EDIT: non-LINQ example (using Contains () from a list class ):

 List<string> names = new List<string> { "Tom", "Jerry", "Tom" }; List<string> distinctNames = new List<string>(); foreach (var name in names) { if (!distinctNames.Contains(name)) { distinctNames.Add(name); } } 
+15
source
 IEnumerable<string> uniqueUsers = list.Distinct(); 

You can also use a HashSet:

 HashSet<string> uniqueUsers = new HashSet<string>(list); 
+22
source

You can use the LINK () LINQ extension.

 var list = new List<string> { "Tom", "Jerry", "Tom" }; var uniqueList = list.Distinct(); 
+6
source

Using Distinct , as suggested in other answers, you leave the original list intact and return a separate IEnumerable<> sequence containing the individual elements from your list.

An alternative would be to remove duplicates from the source list directly using RemoveAll :

 var temp = new HashSet<string>(); yourList.RemoveAll(x => !temp.Add(x)); 
+2
source

you can use list.distinct();

+1
source

All Articles