如何检查词典中是否存在键值对

use*_*466 20 .net c# dictionary data-structures

如何检查字典<>中是否存在键/值对?我能够检查是否存在密钥或值,使用ContainsKeyContainsValue,但我不确定如何检查密钥/值对是否存在.

谢谢

Jon*_*eet 40

好了,如果不能存在关键不存在......所以取与键关联的值,并检查是否这就是你要找的值.例如:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

或稍微"巧妙"(通常要避免......):

public bool ContainsKeyValue(Dictionary<string, int> dictionary,
                             string expectedKey, int expectedValue)
{
    int actualValue;
    return dictionary.TryGetValue(expectedKey, out actualValue) &&
           actualValue == expectedValue;
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 26

字典只支持每个键一个值,因此:

// key = the key you are looking for
// value = the value you are looking for
YourValueType found;
if(dictionary.TryGetValue(key, out found) && found == value) {
    // key/value pair exists
}
Run Code Online (Sandbox Code Playgroud)

  • @CodeInChaos为什么?行为非常明确地定义为始终有效...... (3认同)

Wes*_*ong 6

if (myDic.ContainsKey(testKey) && myDic[testKey].Equals(testValue))
     return true;
Run Code Online (Sandbox Code Playgroud)

  • 请改用TryGetValue. (2认同)