问题
I have a Dictionary, where items are (for example):
- "A", 4
- "B", 44
- "bye", 56
- "C", 99
- "D", 46
- "6672", 0
And I have a List:
- "A"
- "C"
- "D"
I want to remove from my dictionary all the elements whose keys are not in my list, and at the end my dictionary will be:
- "A", 4
- "C", 99
- "D", 46
How can I do?
回答1:
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);
If it's important to modify the existing dictionary (e.g. it's a readonly property of some class)
var keysToRemove = myDictionary.Keys.Except(keysToInclude).ToList();
foreach (var key in keysToRemove)
myDictionary.Remove(key);
Note the ToList() call - it's important to materialize the list of keys to remove. If you try running the code without the materialization of the keysToRemove
, you'll likely to have an exception stating something like "The collection has changed".
回答2:
// 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);
回答3:
dict.Keys.Except(list).ToList()
.ForEach(key => dict.Remove(key));
回答4:
Code:
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);
}
}
Example:
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);
}
Output:
A: 4
C: 99
D: 46
来源:https://stackoverflow.com/questions/13552898/remove-elements-from-dictionarykey-item