checking if list<MyObject> is already in the collection
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?
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 :)
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) ) {
...
}
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.
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();
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
精彩评论