Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting while iterating over a dictionary [duplicate]

Tags:

c#

Possible Duplicate:
Modifying .NET Dictionary while Enumerating through it

I have a dictionary object which I iterate over and do some operations. Based on a condition, I should either delete or keep the key value pair I am currently iterating over. What is the best way to delete a key value pair from a dictionary while iterating over it? I tried to use a separate dictionary object to keep track of the elements to delete, but I'm not sure how to then use it to delete from my main dictionary or if that's even the most efficient way to do it.

like image 956
John Baum Avatar asked Mar 27 '12 15:03

John Baum


2 Answers

Keep a list of the keys you wish to remove as you find them. Then, when you are done, iterate over this list, calling myDictionary.Remove(key) on each key you stored.

like image 79
Rawling Avatar answered Sep 24 '22 17:09

Rawling


Try using a separate dictionary, and instead of marking the key values to delete, insert the key values that you want to keep, and do this at the end of the iteration:

old_map = new_map
like image 39
Euclides Mulémbwè Avatar answered Sep 22 '22 17:09

Euclides Mulémbwè