Nic*_*ick 10 c# collections dictionary list
我有一个词典,其中的项目是(例如):
我有一个清单:
我想从我的字典中删除其键不在我的列表中的所有元素,最后我的字典将是:
我能怎么做?
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,您可能会遇到类似"集合已更改"的异常.
// 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)
dict.Keys.Except(list).ToList()
.ForEach(key => dict.Remove(key));
Run Code Online (Sandbox Code Playgroud)