Remove elements from Dictionary<Key, Item>

 ̄綄美尐妖づ 提交于 2021-02-16 15:51:25

问题


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

And I have a List:

  1. "A"
  2. "C"
  3. "D"

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

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

How can I do?


回答1:


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

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".




回答2:


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



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/13552898/remove-elements-from-dictionarykey-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!