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

.netc++data-structuresdictionary

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

Best Solution

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