Dictionary Keys.Contains vs. ContainsKey: are they functionally equivalent?

陌路散爱 提交于 2019-11-26 23:27:38

问题


I am curious to know if these two are functionally equivalent in all cases.

Is it possible that by changing the dictionary's default comparator that these two would be functionally different?

Also, isn't Keys.Contains almost guaranteed to be slower?


回答1:


These two functions do exactly the same thing.

Keys.Contains exists because Keys is an ICollection<TKey>, which defines a Contains method.
The standard Dictionary<TKey, TValue>.KeyCollection implementation (the class, not the interface) defines it as

bool ICollection<TKey>.Contains(TKey item){ 
    return dictionary.ContainsKey(item); 
}

Since it's implemented explicitly, you can't even call it directly.


You're either seeing the interface, which is what I explained above, or the LINQ Contains() extension method, which will also call the native implementation since it implements ICollection<T>.




回答2:


Although they are pretty much equivalent for Dictionary<,>, I find it's much safer to stick with ContainsKey().

The reason is that in the future you may decide to use ConcurrentDictionary<,> (to make your code thread-safe), and in that implementation, ContainsKey is significantly faster (since accessing the Keys property does a whole bunch of locking and creates a new collection).



来源:https://stackoverflow.com/questions/8235840/dictionary-keys-contains-vs-containskey-are-they-functionally-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!