C# 如何检查字典中是否存在键值对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9650355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:19:41  来源:igfitidea点击:

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

c#.netdata-structuresdictionary

提问by user1261466

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 ContainsKeyand ContainsValue, but I'm unsure of how to check if a key/value pair exist.

如何检查 Dictionary<> 中是否存在键/值对?我可以使用ContainsKeyand检查键或值是否存在,ContainsValue但我不确定如何检查键/值对是否存在。

Thanks

谢谢

回答by Jon Skeet

Well the paircan't exist if the keydoesn'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;
}

回答by Ash Burlaczenko

How something like this

怎么会这样

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

回答by klaustopher

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

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

回答by Marc Gravell

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
}

回答by Wesley Long

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

回答by Md. Mufazzal Hussain

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}

回答by user3454530

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

谢谢,马赫什 G

回答by Philippe Veilleux-Girard

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

回答by Jonathan B.

Simple, Generic Extension Method

简单、通用的扩展方法

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

这是一个快速的通用扩展方法,可将ContainsPair()方法添加到 any 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 Dictionarycase-insensitive with regard to its keys by creating it with a comparer such as StringComparer.OrdinalIgnoreCasewhen the dictionary is constructed.

使用基于字符串的键时,您可以Dictionary通过使用比较器(例如StringComparer.OrdinalIgnoreCase在构造字典时)创建键来使其键不区分大小写。

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

但是,为了使值比较不区分大小写(假设值也是字符串),您可以使用添加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;
}

回答by Nitika Chopra

var result= YourDictionaryName.TryGetValue(key, out string value) ? YourDictionaryName[key] : "";

If the key is present in the dictionary, it returns the value of the key otherwise it returns a blank object.

如果键存在于字典中,则返回键的值,否则返回空对象。

Hope, this code helps you.

希望,此代码可以帮助您。