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.
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.
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
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