tags:

views:

247

answers:

6

I have a List in which I select users from db each time a sql query runs with certain value and selects one user in the time thus I cannot limit identical users in sql.

I have list with:

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

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

Thanks

+15  A: 

LINQ can solve this:

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

If you want a list type, simply call ToList():

distinctItems.ToList();

Here's an example from the MSDN.

EDIT: Non-LINQ Example (using Contains() from the 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);
    }
}
Secret Agent Man
and without LINQ?
eugeneK
Without LINQ? Use traditional search and remove method.
Nayan
See @lee's answer that uses a HashSet instead of LINQ.
Fara
@Fara, i've seen and it is indeed best and most creative answer but @Secret Agent Man answer fits my need more as i haven't provided all the info in my question.
eugeneK
+21  A: 
IEnumerable<string> uniqueUsers = list.Distinct();

You can also use a HashSet:

HashSet<string> uniqueUsers = new HashSet<string>(list);
Lee
+1 for HashSet solution. Neat trick.
Secret Agent Man
+1 for HashSet... great answer
eugeneK
+6  A: 

You can use the Distinct() LINQ extension.

var list = new List<string> { "Tom", "Jerry", "Tom" };

var uniqueList = list.Distinct();
Fara
+1  A: 

you can use list.distinct();

anishmarokey
A: 

Try below

List<string> temp = new List<string>();
temp.Distinct();
saurabh
+2  A: 

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

An alternative would be to remove duplicates from your original list directly, using RemoveAll:

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