C# 从 Dictionary<Key, Item> 中删除元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13552898/
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-10 08:58:43  来源:igfitidea点击:

Remove elements from Dictionary<Key, Item>

c#listcollectionsdictionary

提问by Nick

I have a Dictionary, where items are (for example):

我有一个字典,其中的项目是(例如):

  1. "A", 4
  2. "B", 44
  3. "bye", 56
  4. "C", 99
  5. "D", 46
  6. "6672", 0
  1. "A", 4
  2. “乙”,44
  3. “再见”, 56
  4. "C", 99
  5. “D”,46
  6. "6672", 0

And I have a List:

我有一个列表:

  1. "A"
  2. "C"
  3. "D"
  1. “一种”
  2. “C”
  3. “丁”

I want to remove from my dictionary all the elements whose keys are notin my list, and at the end my dictionary will be:

我想从我的字典中删除所有键不在我列表中的元素,最后我的字典将是:

  1. "A", 4
  2. "C", 99
  3. "D", 46
  1. "A", 4
  2. "C", 99
  3. “D”,46

How can I do?

我能怎么做?

采纳答案by J0HN

It's simpler to construct new Dictionary to contain elements that are in the list:

构造新的 Dictionary 以包含列表中的元素更简单:

List<string> keysToInclude = new List<string> {"A", "B", "C"};
var newDict = myDictionary
     .Where(kvp=>keysToInclude.Contains(kvp.Key))
     .ToDictionary(kvp=>kvp.Key, kvp=>kvp.Value);

If it's important to modify the existing dictionary (e.g. it's a readonly property of some class)

如果修改现有字典很重要(例如,它是某个类的只读属性)

var keysToRemove = myDictionary.Keys.Except(keysToInclude).ToList();

foreach (var key in keysToRemove)
     myDictionary.Remove(key);

Note the ToList() call - it's important to materialize the list of keys to remove. If you try running the code without the materialization of the keysToRemove, you'll likely to have an exception stating something like "The collection has changed".

请注意 ToList() 调用 - 实现要删除的键列表很重要。如果您尝试在没有实现 的情况下运行代码keysToRemove,您可能会遇到诸如“集合已更改”之类的异常。

回答by Joachim Isaksson

// For efficiency with large lists, for small ones use myList below instead.  
var mySet = new HashSet<string>(myList);

// Create a new dictionary with just the keys in the set
myDictionary = myDictionary
               .Where(x => mySet.Contains(x.Key))
               .ToDictionary(x => x.Key, x => x.Value);

回答by SimpleVar

Code:

代码:

public static void RemoveAll<TKey, TValue>(this Dictionary<TKey, TValue> target,
                                           List<TKey> keys)
{
    var tmp = new Dictionary<TKey, TValue>();

    foreach (var key in keys)
    {
        TValue val;
        if (target.TryGetValue(key, out val))
        {
            tmp.Add(key, val);
        }
    }

    target.Clear();

    foreach (var kvp in tmp)
    {
        target.Add(kvp.Key, kvp.Value);
    }
}

Example:

例子:

var d = new Dictionary<string, int>
            {
                {"A", 4},
                {"B", 44},
                {"bye", 56},
                {"C", 99},
                {"D", 46},
                {"6672", 0}
            };

var l = new List<string> {"A", "C", "D"};

d.RemoveAll(l);

foreach (var kvp in d)
{
    Console.WriteLine(kvp.Key + ": " + kvp.Value);
}

Output:

输出:

A: 4
C: 99
D: 46

回答by L.B

dict.Keys.Except(list).ToList()
    .ForEach(key => dict.Remove(key));