Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
506 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
...