How to check if a key/value pair exists in a Dictionary?

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)