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

时间:2021-01-02 23:46:39

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.

如何检查词典<>中是否存在键/值对?我可以使用ContainsKey和ContainsValue检查密钥或值是否存在,但我不确定如何检查密钥/值对是否存在。

Thanks

谢谢

9 个解决方案

#1


36  

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

#2


22  

A dictionary only supports one value per key, so:

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

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

#3


4  

if (myDic.ContainsKey(testKey) && myDic[testKey].Equals(testValue))
     return true;

#4


3  

You can do this by using dictionary.TryGetValue.

您可以使用dictionary.TryGetValue来完成此操作。

Dictionary<string, bool> clients = new Dictionary<string, bool>();
                    clients.Add("abc", true);
                    clients.Add("abc2", true);
                    clients.Add("abc3", false);
                    clients.Add("abc4", true);

                    bool isValid = false;

                    if (clients.TryGetValue("abc3", out isValid)==false||isValid == false)
                    {
                        Console.WriteLine(isValid);
                    }
                    else
                    {
                        Console.WriteLine(isValid);
                    }

At the above code if condition there is two sections first one for checking key has value and second one for comparing the actual value with your expected value.

在上面的代码中,如果条件有两个部分,则第一个用于检查键有值,第二个用于比较实际值和预期值。

First Section{clients.TryGetValue("abc3", out isValid)==false}||Second Section{isValid == false}

#5


0  

How something like this

这是怎么回事

bool exists = dict.ContainsKey("key") ? dict["key"] == "value" : false;

#6


0  

Generic version of Jon Skeet's answer

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

#7


0  

Simple, Generic Extension Method

简单的通用扩展方法

Here's a quick generic extension method that adds a ContainsPair() method to any IDictionary:

这是一个快速的通用扩展方法,它将ContainsPair()方法添加到任何IDictionary:

public static bool ContainsPair<TKey, TValue>(this IDictionary<TKey, TValue> dictionary,
                                                   TKey key,
                                                   TValue value)
{
    return dictionary.TryGetValue(key, out var found) && found.Equals(value);
}

This allows you to do checks against dictionaries like this:

这允许您对这样的字典进行检查:

if( myDict.ContainsPair("car", "mustang") ) { ... }     // NOTE: this is not case-insensitive

Case-Insensitive Check

不区分大小写

When working with string-based keys, you can make the Dictionary case-insensitive with regard to its keys by creating it with a comparer such as StringComparer.OrdinalIgnoreCase when the dictionary is constructed.

使用基于字符串的键时,通过在构造字典时使用比较器(如StringComparer.OrdinalIgnoreCase)创建字典,可以使字典对其键不敏感。

However, to make the value comparison case insensitive (assuming the values are also strings), you can use this version that adds an IComparer parameter:

但是,要使值比较不区分大小写(假设值也是字符串),您可以使用此版本添加IComparer参数:

public static bool ContainsPair<TKey, TValue>(this IDictionary<TKey, TValue> dictionary,
                                                   TKey key,
                                                   TValue value,
                                                   IComparer<TValue> comparer)
{
    return dictionary.TryGetValue(key, out var found) && comparer.Compare(found, value) == 0;
}

#8


-1  

First you check if the key exists, if so, you get the value for this key and compare it to the value you are testing... If they are equal, your Dictionary contains the pair

首先检查密钥是否存在,如果是,则获取此密钥的值并将其与您正在测试的值进行比较...如果它们相等,则您的字典包含该对

#9


-4  

Please check with following code

请检查以下代码

var dColList = new Dictionary<string, int>();
if (!dColList.Contains(new KeyValuePair<string, int>(col.Id,col.RowId)))
{}

Thanks, Mahesh G

谢谢,Mahesh G.

#1


36  

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

#2


22  

A dictionary only supports one value per key, so:

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

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

#3


4  

if (myDic.ContainsKey(testKey) && myDic[testKey].Equals(testValue))
     return true;

#4


3  

You can do this by using dictionary.TryGetValue.

您可以使用dictionary.TryGetValue来完成此操作。

Dictionary<string, bool> clients = new Dictionary<string, bool>();
                    clients.Add("abc", true);
                    clients.Add("abc2", true);
                    clients.Add("abc3", false);
                    clients.Add("abc4", true);

                    bool isValid = false;

                    if (clients.TryGetValue("abc3", out isValid)==false||isValid == false)
                    {
                        Console.WriteLine(isValid);
                    }
                    else
                    {
                        Console.WriteLine(isValid);
                    }

At the above code if condition there is two sections first one for checking key has value and second one for comparing the actual value with your expected value.

在上面的代码中,如果条件有两个部分,则第一个用于检查键有值,第二个用于比较实际值和预期值。

First Section{clients.TryGetValue("abc3", out isValid)==false}||Second Section{isValid == false}

#5


0  

How something like this

这是怎么回事

bool exists = dict.ContainsKey("key") ? dict["key"] == "value" : false;

#6


0  

Generic version of Jon Skeet's answer

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

#7


0  

Simple, Generic Extension Method

简单的通用扩展方法

Here's a quick generic extension method that adds a ContainsPair() method to any IDictionary:

这是一个快速的通用扩展方法,它将ContainsPair()方法添加到任何IDictionary:

public static bool ContainsPair<TKey, TValue>(this IDictionary<TKey, TValue> dictionary,
                                                   TKey key,
                                                   TValue value)
{
    return dictionary.TryGetValue(key, out var found) && found.Equals(value);
}

This allows you to do checks against dictionaries like this:

这允许您对这样的字典进行检查:

if( myDict.ContainsPair("car", "mustang") ) { ... }     // NOTE: this is not case-insensitive

Case-Insensitive Check

不区分大小写

When working with string-based keys, you can make the Dictionary case-insensitive with regard to its keys by creating it with a comparer such as StringComparer.OrdinalIgnoreCase when the dictionary is constructed.

使用基于字符串的键时,通过在构造字典时使用比较器(如StringComparer.OrdinalIgnoreCase)创建字典,可以使字典对其键不敏感。

However, to make the value comparison case insensitive (assuming the values are also strings), you can use this version that adds an IComparer parameter:

但是,要使值比较不区分大小写(假设值也是字符串),您可以使用此版本添加IComparer参数:

public static bool ContainsPair<TKey, TValue>(this IDictionary<TKey, TValue> dictionary,
                                                   TKey key,
                                                   TValue value,
                                                   IComparer<TValue> comparer)
{
    return dictionary.TryGetValue(key, out var found) && comparer.Compare(found, value) == 0;
}

#8


-1  

First you check if the key exists, if so, you get the value for this key and compare it to the value you are testing... If they are equal, your Dictionary contains the pair

首先检查密钥是否存在,如果是,则获取此密钥的值并将其与您正在测试的值进行比较...如果它们相等,则您的字典包含该对

#9


-4  

Please check with following code

请检查以下代码

var dColList = new Dictionary<string, int>();
if (!dColList.Contains(new KeyValuePair<string, int>(col.Id,col.RowId)))
{}

Thanks, Mahesh G

谢谢,Mahesh G.