我有一个词典,其中的项目是(例如):
我有一个清单:
我想从我的词典中删除我的列表中键不的所有元素,最后我的词典将是:
我该怎么办?
答案 0 :(得分:17)
构造新的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);
如果修改现有字典很重要(例如,它是某个类的只读属性)
var keysToRemove = myDictionary.Keys.Except(keysToInclude).ToList();
foreach (var key in keysToRemove)
myDictionary.Remove(key);
注意ToList()调用 - 实现要删除的键列表很重要。如果您尝试在没有实现keysToRemove
的情况下运行代码,您可能会遇到类似“集合已更改”的异常。
答案 1 :(得分:7)
// 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);
答案 2 :(得分:4)
dict.Keys.Except(list).ToList()
.ForEach(key => dict.Remove(key));
答案 3 :(得分:0)
<强>代码:强>
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);
}
}
示例:强>
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);
}
<强>输出:强>
A: 4
C: 99
D: 46