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?
Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.
The default constructor of C# Dictionary class constructs a Dictionary object, in which the keys are case sensitive. So when you insert data pairs <Key, Value> and <key, Value>, they are regarded as two different items.
TryGetValue Method: This method combines the functionality of the ContainsKey method and the Item property. If the key is not found, then the value parameter gets the appropriate default value for the value type TValue; for example, 0 (zero) for integer types, false for Boolean types, and null for reference types.
ContainsKey is a Dictionary method in C# and check whether a key exists in the Dictionary or not. Declare a Dictionary and add elements − var dict = new Dictionary<string, int>() { {"TV", 1}, {"Home Theatre", 2}, {"Amazon Alexa", 3}, {"Google Home", 5}, {"Laptop", 5}, {"Bluetooth Speaker", 6} };
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>
.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With