Checking if the list <MyObject> is already in the collection

usually with a hash table:

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

      

If I have a list, how can I check the usage contains?

Right now I just create a hash table of custom ids and validation, but is there a way to just use just a list?

+2


source to share


5 answers


You can use List<T>.Contains

- just remember that this will be a linear search, i.e. O (N), not O (1) a HashMap

. If your list is not too long, this is unlikely to be a problem. Of course, you still need the elements to override correctly Equals

if you're not happy with the reference id.



If you have a large list that you will need for repeated containment tests, you can simply create HashSet<T>

from the existing list. If you are going to manipulate the list a lot, you can encapsulate both the list and the set together into your own collection. You will need to decide what semantics you want - what would you like if you added the same identifier twice? Should I ignore the second challenge? If you can get away without doing it, so much the better :)

+7


source


Is there any reason why List.Contains isn't working?

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

      



If id is a property in MyObject you can do the following

if ( !myList.Any(x => x.Id == someId) ) {
  ...
}

      

+4


source


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

+1


source


You can also do

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

      

if 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 this can also be done with

bool listContainsId = (from item in list
                            where item.Id == someOtherValue
                            select item).Any();

      

+1


source


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

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

0


source







All Articles