Suppose:
Dictionary<Guid, MyClass> dict;
Is there any difference between
dict.Keys.Contains(key)
dict.ContainsKey(key)
I thought there was no difference, but I am not sure now.
Suppose:
Dictionary<Guid, MyClass> dict;
Is there any difference between
dict.Keys.Contains(key)
dict.ContainsKey(key)
I thought there was no difference, but I am not sure now.
These two methods are guaranteed to return the same true
/false
value.
According to reference implementation, dict.Keys.Contains(key)
delegates to dict.ContainsKey(key)
:
bool ICollection<TKey>.Contains(TKey item){
return dictionary.ContainsKey(item);
}
This method is part of KeyCollection
class. Its dictionary
field refers to the Dictionary
object that owns the KeyCollection
returned by Keys
property.
The first line retrieves the keys collection before searching for the key, while the second line searches the dictionary's keys directly avoiding an extra step.
According to the documentation for the Dictionary.Keys property, accessing the collection is a constant time operation and does not involve creating a copy of the entire set of dictionary keys. Thus there appears to be little difference between the two operations aside from the additional step of retrieving the keys collection before searching for the key.
All things being equal, I would personally prefer the second version because it skips the extra step and conveys your intent more concisely.
A Dictionary is optimized for looking up keys.
With dict.ContainsKey(key)
you would be sure to use that optimized search.
When you use dict.Keys.Contains(key)
you are more dependent on the implementation. The naive route would first get an IEnumerable<TKey>
and then do the (linear) lookup. The actual library class might be smarter but you would always have to look up the source to be sure.