【问题标题】:How to check for duplicate keys and delete previous value from Dictionary?如何检查重复键并从字典中删除以前的值?
【发布时间】:2014-03-10 11:04:42
【问题描述】:

我有一个Dictionary,其中包含带有键的值。根据我的情况,我将拥有Dictionary 中严格不允许的重复键。现在我的问题是:如何检查当前Dictionary中的先前重复键并删除它以添加新的?

【问题讨论】:

    标签: c# dictionary


    【解决方案1】:

    您可以使用 Dictionary 的 ContainsKey() 方法来查看 Dictionary 是否已经包含您的密钥

    dict.ContainsKey(Key)
    

    如果字典包含键,它返回 true,否则返回false

    不需要删除你可以覆盖值的键

    if(dict.ContainsKey(Key))
    {
    dict[key]=YOUR_NEW_VALUE;
    }
    else
    {
     dict.Add ( key,YOUR_NEW_VALUE);
    }
    

    【讨论】:

      【解决方案2】:

      我的建议是将删除视为简单地覆盖匹配条目的 Value 成员。

      if (myDictionary.ContainsKey("key"))
      {
          myDictionary["key"] = newValue;
      }
      

      【讨论】:

        【解决方案3】:

        通过使用ContainsKey()

        if(dict.ContainsKey(YourKey))
            dict[YourKey] = YourNewValue;
        

        dict 是您的字典。

        这一行将新值覆盖到键:

        dict[YourKey] = YourNewValue;
        

        【讨论】:

          【解决方案4】:

          使用 ContainsKey 方法查找现有密钥,如下所示:

           if (yourdictc.ContainsKey("YourKey"))
             { 
               //Do Somethig
             } 
          

          【讨论】:

            【解决方案5】:
            var uniqueValues = myDict.GroupBy(pair => pair.Value)
                                     .Select(group => group.First())
                                     .ToDictionary(pair => pair.Key, pair => pair.Value);
            

            【讨论】:

              【解决方案6】:

              如果您想要添加或更新行为,则无需调用 ContainsKey。只需分配值,如果密钥存在,它将被更新。如果没有,则会添加。

              dict[key] = newValue;
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2013-04-08
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2020-03-24
                • 1970-01-01
                相关资源
                最近更新 更多