如何检查Dictionary<>中是否存在键/值对?我可以使用ContainsKey和ContainsValue检查键或值是否存在,但我不确定如何检查键/值对是否存在。
谢谢
发布于 2012-03-11 05:36:52
一个字典只支持每个key一个值,所以:
// 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
}发布于 2012-03-11 05:36:53
if (myDic.ContainsKey(testKey) && myDic[testKey].Equals(testValue))
return true;发布于 2017-11-16 23:46:54
Jon Skeet答案的通用版本
public bool ContainsKeyValue<TKey, TVal>(Dictionary<TKey, TVal> dictionnaire,
TKey expectedKey,
TVal expectedValue) where TVal : IComparable
{
TVal actualValue;
if (!dictionnaire.TryGetValue(expectedKey, out actualValue))
{
return false;
}
return actualValue.CompareTo(expectedValue) == 0;
}https://stackoverflow.com/questions/9650355
复制相似问题