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.
The Python del statement deletes an object. Because key-value pairs in dictionaries are objects, you can delete them using the “del” keyword. The “del” keyword is used to delete a key that does exist. It raises a KeyError if a key is not present in a dictionary.
Use del if you want to delete an item from a dictionary.
You could use Enumerable.Except
to find the keys that are not in the dictionary:
foreach (var key in MyDictionary.Keys.Except(AllowedList).ToList())
MyDictionary.Remove(key);
The ToList()
creates a new list of the set difference and prevents the exception.
You could/should store the keys you want to delete in a temporary list and do all the removing in an extra for-loop after that.
List<TKey> templist = new List<TKey>();
foreach (var x in MyDictionary)
{
if (!AllowedList.Contains(x.Key))
templist .Add(x.Key);
}
foreach (TKey item in templist )
{
MyDictionary.Remove(item);
}
this could also be helpful: How to delete entries from a dictionary using the value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With