Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting key,value pairs from a dictionary given a list of keys to delete

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.

like image 215
user17753 Avatar asked Oct 09 '12 19:10

user17753


People also ask

Can we remove key value pair from dictionary Python?

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.

Which method should you use if you want to delete an item from a dictionary?

Use del if you want to delete an item from a dictionary.


2 Answers

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.

like image 106
Tim Schmelter Avatar answered Oct 02 '22 08:10

Tim Schmelter


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

like image 30
Seismoid Avatar answered Oct 02 '22 08:10

Seismoid