18

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.

Pang
  • 9,564
  • 146
  • 81
  • 122
John Baum
  • 3,183
  • 11
  • 42
  • 90

2 Answers2

23

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.

Rawling
  • 49,248
  • 7
  • 89
  • 127
  • 8
    that would mean 2 iterations, one to get the files to delete and other to delete the items, why not just copy the items you don't want to delete to the other dictionary? – Euclides Mulémbwè Mar 27 '12 at 15:41
  • 1
    @Euclides - I'd honestly not thought of that. Without a compelling reason to end up with the same dictionary, modified, I'd expect that to be more efficient in most cases. – Rawling Mar 27 '12 at 15:48
  • 6
    "why not just copy the items you don't want to delete to the other dictionary?" If the number of items that are expected to be removed are very few or removals are seldom, this would be very inperformant. So recommendations depend on the data access pattern – Imi Apr 26 '17 at 18:20
8

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
Pang
  • 9,564
  • 146
  • 81
  • 122
Euclides Mulémbwè
  • 1,677
  • 11
  • 18