I have a List<string> AllowedList and a Dictionary<string,List<string>> MyDictionary.
For each key in the dictionary, I want to check if it’s on the AllowedList, if not I want to delete the key and value from the dictionary.
I intuitively tried this which seems to be what I wanted:
foreach (string key in MyDictionary.Keys)
{
if (!AllowedList.Contains(key)) MyDictionary.Remove(key);
}
However, I encountered an InvalidOperationException:
Collection was modified; enumeration operation may not execute.
I’m sure there’s probably a simple way around this, but I don’t immediately see it.
You could use
Enumerable.Exceptto find the keys that are not in the dictionary:The
ToList()creates a new list of the set difference and prevents the exception.