【问题标题】:How to check if a key,value pair exists in a Dictionary如何检查字典中是否存在键值对
【发布时间】:2012-03-27 20:46:58
【问题描述】:

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

谢谢

【问题讨论】:

    标签: c# .net data-structures dictionary


    【解决方案1】:

    如果 key 不存在,则 pair 将不存在...所以获取与该键关联的值,并检查这是否是您的值正在寻找。比如:

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

    或者稍微更“聪明”(通常是要避免的事情......):

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

    【讨论】:

      【解决方案2】:

      怎么会这样

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          字典只支持每个键一个值,所以:

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

          【讨论】:

          • 我有点不喜欢在一个表达式中设置和使用found。
          • 我知道它的定义很明确。这只是一种风格偏好。就像我试图让每个语句只有一个副作用一样,这也是该语句中发生的最后一件事。
          【解决方案5】:
          if (myDic.ContainsKey(testKey) && myDic[testKey].Equals(testValue))
               return true;
          

          【讨论】:

          • 是的,它有效。这不是说明性的。我选择这个是为了让逻辑清晰,而不是优化性能。
          • 我们谈论的这个特殊场景不是关于(微)优化。更多的是了解 .NET 字典的工作原理、O(k) 复杂性等。在这里使用 trygetvalue 是正确的做法。
          【解决方案6】:

          您可以使用 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);
                              }
          

          在上面的代码中,如果条件有两个部分,第一个用于检查键是否具有值,第二个用于将实际值与您的期望值进行比较。

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

          【讨论】:

            【解决方案7】:

            请检查以下代码

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

            谢谢, 马赫什G

            【讨论】:

            • 这将比其他选项慢 很多,因为您没有利用字典功能对其键进行快速查找。
            • @Servy 在这种情况下查找速度非常快。 Dictionary.cs 中的实际实现首先通过 Key 查找字典条目,然后比较 Value。这个答案提供了一个非常优雅和快速的解决方案。
            • @petrsyn Dictionary&lt;TKey,TValue&gt; 没有 Contains 方法。这是使用 IEnumerable&lt;T&gt; 的 LINQ 扩展,它对序列进行线性搜索,并且无法使用字典根据其哈希查找键的能力。这里还有许多其他答案可以使用字典的实际方法正确地做到这一点,这些方法利用了它的快速搜索。
            • @petrsyn 为什么你认为它被调用了?我并不是说该方法不可调用,我只是说这段代码没有调用它,它调用的是不同的方法,具有不同的实现。只有当表达式的编译时类型是该接口时才会调用显式接口实现,这里不是这种情况。
            • @Servy Dictionary 类实现接口IDictionary&lt;TKey, TValue&gt; 扩展ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; 并且方法签名是bool ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.Contains(KeyValuePair&lt;TKey, TValue&gt; keyValuePair)。因此Dictionary类实现了接口方法,会被调用。
            【解决方案8】:

            Jon Skeet's answer的通用版本

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

            【讨论】:

              【解决方案9】:

              简单的通用扩展方法

              这是一个快速的通用扩展方法,它将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);
              }
              

              这使您可以像这样对字典进行检查:

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

              不区分大小写的检查

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

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

              【讨论】:

                【解决方案10】:
                var result= YourDictionaryName.TryGetValue(key, out string value) ? YourDictionaryName[key] : "";
                

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

                希望这段代码能帮到你。

                【讨论】:

                  猜你喜欢
                  • 2016-03-20
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2012-01-03
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多