关于c#:如果值与多个键匹配,则从字典中删除所有键


Delete all the keys from the dictionary if the value matches for more than one key

我有一本字典

1
private readonly Dictionary<string, WebResponse> _myDictionary;

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

删除:

1
_myDictionary.Remove(Key);

其中键是字符串变量。

如果值与多个键匹配,是否可以一次删除多个键。我有kaar1、kaar2、kaar3、abcdef等键。现在我需要删除所有包含"kaar"的密钥。有可能吗?

请帮忙。

  • 试试这个:_myDictionary.Where(x => x.Key.Contains("KAAR")).ToList().ForEach(kvp => _myDictionary.Remove(kvp.Key));
  • @神秘莫测,你为什么不加上这个作为答案呢?我觉得这个主意不错
  • 请检查此问题以了解执行相同stackoverflow.com/questions/469202/&hellip;的更多方法。
  • @神秘性-你的答案毫无问题。非常感谢!


试试这个:

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

  • 为什么是ToList()
  • @?????????????可能是因为这样不会创建新字典
  • @??????????????因为IEnumerable中的输出不能应用foreach循环。这就是为什么需要转换成列表。
  • @??????????????—.ToList()调用还强制对字典进行完全枚举,以便.Remove(...)调用在枚举时不会更改字典。正如艾哈迈德所说,访问.ForEach(...)扩展方法。
  • 谢谢。我不死。
  • 一个小提示:使用扩展方法对列表和字典非常有益,因为它允许使用这样的语法:ListObj.YourMethod ();,而且这个问题似乎需要一个适用于泛型类型的通用解决方案。
  • @战斗-对不起,我不明白。你说的ListObj.YourMethod();是什么意思?
  • @神秘性——它不是针对你个人的,也不是任何批评——你的回答很好。我只是想指出,所有这些都可以用泛型包装成一个扩展方法…在下面的答案中,我也为它添加了代码。


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/// <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。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/// <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次执行,其中第一次执行之后的所有操作都将过时)。代码已经过测试和工作。


下面是用户@enigmavity给出的答案!!作为单独答案添加,以标记为正确答案。

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