【问题标题】:Delete all the keys from the dictionary if the value matches for more than one key如果值与多个键匹配,则从字典中删除所有键
【发布时间】:2018-12-24 17:54:07
【问题描述】:

我有一本字典

private readonly Dictionary<string, WebResponse> _myDictionary;

假设我目前在字典中有 10 个值。我可以向其中添加一些值,也可以根据字典中存在的键删除值,如下所示。

删除:

_myDictionary.Remove(Key); 

其中 key 是一个字符串变量。

如果值匹配多个键,是否可以一次删除多个键。我有像 {KAAR1, KAAR2, KAAR3, ABCDEF} 这样的键。现在我需要删除所有包含“KAAR”的键。有可能吗。

请帮忙。

【问题讨论】:

  • 试试这个:_myDictionary.Where(x =&gt; x.Key.Contains("KAAR")).ToList().ForEach(kvp =&gt; _myDictionary.Remove(kvp.Key));.
  • @Enigmativity 为什么不将此添加为答案。对我来说这是个好主意
  • 查看这个问题以了解更多方法来做同样的事情*.com/questions/469202/…
  • @Enigmativity - 您的回答没有任何问题。非常感谢!

标签: c#


【解决方案1】:

试试这个:

_myDictionary
    .Where(x => x.Key.Contains("KAAR"))
    .ToList()
    .ForEach(kvp => _myDictionary.Remove(kvp.Key));

【讨论】:

  • 为什么是ToList()
  • @חייםפרידמן 可能是因为这样它不会创建 new 字典
  • @חייםפרידמן 因为在 IEnumerable 中的输出我们无法应用 Foreach 循环。这就是为什么需要转换为 LIST 的原因。
  • @חייםפרידמן - .ToList() 调用还强制字典的完整枚举,以便.Remove(...) 调用在枚举时不会更改字典。而且,正如 Ahmad 所说,要访问 .ForEach(...) 扩展方法。
  • 谢谢。我不明白。
【解决方案2】:

以下是网友@Enigmavitivity给出的答案!! 添加为单独的答案以标记为正确答案。

_myDictionary.Where(x => x.Key.Contains("KAAR")).ToList().ForEach(kvp => _myDictionary.Remove(kvp.Key));

【讨论】:

    【解决方案3】:

    我扩展了@Enigmativity 的答案,提供了两个通用版本作为扩展方法。

    /// <summary> Removes all duplicate values after the first occurrence. </summary>
    public static void RemoveDuplicates<T, V> (this Dictionary<T, V> dict)
    {
        List<V> L = new List<V> ();
        int i = 0;
        while (i < dict.Count)
        {
            KeyValuePair<T, V> p = dict.ElementAt (i);
            if (!L.Contains (p.Value))
            {
                L.Add (p.Value);
                i++;
            }
            else
            {
                dict.Remove (p.Key);
            }
        }
    }
    

    使用值字典(忽略键):0、1、2、3、5、1、2、4、5。 结果:0、1、2、3、5、4。

    /// <summary> Removes all values which have any duplicates. </summary>
    public static void RemoveAllDuplicates<T, V> (this Dictionary<T, V> dict)
    {
        List<V> L = new List<V> ();
        int i = 0;
        while (i < dict.Count)
        {
            KeyValuePair<T, V> p = dict.ElementAt (i);
            if (!L.Contains (p.Value))
            {
                L.Add (p.Value);
                i++;
            }
            else
            {
                dict.Where (j => Equals (j.Value, p.Value)).ToList ().ForEach (j => dict.Remove (j.Key));
            }
        }
    }
    

    使用值字典(忽略键):0、1、2、3、5、1、2、4、5。 结果:3、4。

    这些方法经过优化以防止多次执行 .Where 操作(否则每个副本都会执行 n 次,第一个之后的所有操作都已过时)。代码已经过测试并且可以运行。

    【讨论】: