tags:

views:

93

answers:

5

normally with a hashtable I do:

if(!myHash.Contains(someId))
{
   // insert to hash
}

If I have a List, how can I check using contains?

Right now I am just creating a hashtable of user id's, and checking that, but is there a way just using just the List?

+7  A: 

You can use List<T>.Contains - just be aware that it will be a linear search, i.e. O(N) instead of the O(1) of a HashMap. If your list isn't too large, it's unlikely to be much of a problem. Of course, you still need the items to override Equals appropriately unless you're happy with reference identity.

If you've got a large list which you'll need to do repeated containment tests on, you may just want to create a HashSet<T> from the existing list. If you're going to be manipulating the list a lot as you go, you may want to encapsulate both the list and the set together in your own collection. You'll need to work out which semantics you want though - what would you want to happen if you added the same ID twice? Should the second call be ignored? If you can get away without doing this, so much the better :)

Jon Skeet
+4  A: 

Is there a reason that List.Contains does no work?

if ( !myList.Contains(someId) ) {
  ...
}

If the ID is a property on MyObject then you could do the following

if ( !myList.Any(x => x.Id == someId) ) {
  ...
}
JaredPar
+1  A: 

You can use the List.Contains method. However, note that this method does a linear search and is therefore slower than a Hashtable. If you have a large number of users, consider using a HashSet.

SLaks
+1  A: 

You can also do

list.Find(x => x.Id == someOtherValue) != null

in case you need support in C# 2.0 it can be written like this

list.Find(delegate(Agent x) { return x.Id == someOtherValue; }) != null

For LINQ it could also be done with

bool listContainsId = (from item in list
                            where item.Id == someOtherValue
                            select item).Any();
Chris Marisic
woohoo for Linq!
gmcalab
Actually that's not using LINQ, it's just using the lambda operator to create inline delegate method. JaredPar's example using the .Any method is LINQ.
Chris Marisic
A: 

Have you considered put it into a SortedList then the search will be binary search. This method is an O(log n) operation, where n is Count.

http://msdn.microsoft.com/en-us/library/system.collections.sortedlist.contains.aspx

Chenster
Unfortunately, there is no generic version of SortedList.
SLaks
Yes, there is. http://msdn.microsoft.com/en-us/library/ms132319.aspx
Chenster