Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a key,value pair exists in a Dictionary

How can one check if a key/value pair exists in a Dictionary<>? I'm able to check if a key or value exist, using ContainsKey and ContainsValue, but I'm unsure of how to check if a key/value pair exist.

Thanks

like image 757
user1261466 Avatar asked Mar 10 '12 21:03

user1261466


People also ask

How do you check if a key exists in a dictionary or not?

How do you check if a key exists or not in a dictionary? You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key(). 2.

How do you check if a key-value pair exists in a dictionary C#?

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.

How do you check if a value exists in a list of dictionaries?

Use any() & List comprehension to check if a value exists in a list of dictionaries.


1 Answers

Well the pair can't exist if the key doesn't exist... so fetch the value associated with the key, and check whether that's the value you were looking for. So for example:

// Could be generic of course, but let's keep things simple... public bool ContainsKeyValue(Dictionary<string, int> dictionary,                              string expectedKey, int expectedValue) {     int actualValue;     if (!dictionary.TryGetValue(expectedKey, out actualValue))     {         return false;     }     return actualValue == expectedValue; } 

Or slightly more "cleverly" (usually something to avoid...):

public bool ContainsKeyValue(Dictionary<string, int> dictionary,                              string expectedKey, int expectedValue) {     int actualValue;     return dictionary.TryGetValue(expectedKey, out actualValue) &&            actualValue == expectedValue; } 
like image 124
Jon Skeet Avatar answered Sep 24 '22 22:09

Jon Skeet