【发布时间】:2012-11-13 05:23:08
【问题描述】:
我有一个字典,其中项目(例如):
- “A”,4
- “B”,44
- “再见”,56
- “C”,99
- “D”,46
- “6672”,0
我有一个列表:
- “A”
- “C”
- “D”
我想从我的字典中删除所有键在我的列表中不的元素,最后我的字典将是:
- “A”,4
- “C”,99
- “D”,46
我该怎么办?
【问题讨论】:
标签: c# list collections dictionary
我有一个字典,其中项目(例如):
我有一个列表:
我想从我的字典中删除所有键在我的列表中不的元素,最后我的字典将是:
我该怎么办?
【问题讨论】:
标签: c# list collections dictionary
构造新 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 的情况下运行代码,您可能会遇到类似“集合已更改”的异常。
【讨论】:
// 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);
【讨论】:
dict.Keys.Except(list).ToList()
.ForEach(key => dict.Remove(key));
【讨论】:
代码:
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
【讨论】: