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

Nic*_*ick 10 c# collections dictionary list

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

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

我有一个清单:

  1. "一个"
  2. "C"
  3. "d"

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

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

我能怎么做?

J0H*_*0HN 17

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);
Run Code Online (Sandbox Code Playgroud)

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

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

foreach (var key in keysToRemove)
     myDictionary.Remove(key);
Run Code Online (Sandbox Code Playgroud)

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


Joa*_*son 8

// 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);
Run Code Online (Sandbox Code Playgroud)

  • @ J0HN人们会不会不恰当地发布这个链接?这不是为时过早,而不是"优化".优化是您获取代码并进行一些调整的地方,因此它可以更快地执行.这是一个完全不同的算法,你甚至不能说这是不成熟的,因为我所拥有的只是OP的问题,我没有做他的项目. (3认同)

L.B*_*L.B 5

dict.Keys.Except(list).ToList()
    .ForEach(key => dict.Remove(key));
Run Code Online (Sandbox Code Playgroud)