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?
It’s simpler to construct new Dictionary to contain elements that are in the list:
If it’s important to modify the existing dictionary (e.g. it’s a readonly property of some class)
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”.