我有一个字典,其中项目是(例如):
- “一”,4
- “乙”,44
- “再见”,56
- “C”,99
- “D”,46
- "6672", 0
我有一个清单:
- “一种”
- “C”
- “D”
我想从我的字典中删除所有键不在我列表中的元素,最后我的字典将是:
- “一”,4
- “C”,99
- “D”,46
我能怎么做?
我有一个字典,其中项目是(例如):
我有一个清单:
我想从我的字典中删除所有键不在我列表中的元素,最后我的字典将是:
我能怎么做?
构造新 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