Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 733
user420667 Avatar asked Nov 23 '11 00:11

user420667


People also ask

How do you check if a key exists in a dictionary c3?

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.

Is Dictionary ContainsKey case sensitive C#?

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.

How does TryGetValue work C#?

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.

What is ContainsKey C#?

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} };


2 Answers

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

like image 155
SLaks Avatar answered Oct 30 '22 08:10

SLaks


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

like image 41
RobSiklos Avatar answered Oct 30 '22 10:10

RobSiklos