Checking if the list <MyObject> is already in the collection
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 :)
source to share
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 .
source to share
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();
source to share
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
source to share