[Solved] Difference between ContainsKey and ContainsValue in Dictionary?


Dictionarys are mappings from a key to a value.

ContainsKey() checks if your dictionary contains a certain key, it is very fast – looking up keys (and finding the data associated with that key) is the main strength of dictionaries. You might need this, to avoid accessing a non-existent Key – read about TryGetValue() in that case – it might be a better choice to avoid accessing non existing keys data.

ContainsValue() iterates over all values and checks if it is in the dictionary, it is a slow and cumbersome procedure because it needs to go to all values until the first one matches. Accessing values not by its key, but by iterating all is not what dictionaries are about.

Doing a ContainsKey() is fine, if you feel you need to do a ContainsValue() you are probably operating on the wrong kind of data structure.

Doku:

1

solved Difference between ContainsKey and ContainsValue in Dictionary?