views:

26

answers:

1

.NET 2

The standard:

  foreach(KeyValuePair<int,int> entry in MyDic)
  {
      entry.Value += i; // does not work :(
      i++;
  }

Recommendations?

+4  A: 

Loop over the Keys property instead. When you use enumerators, any modification to the underlying collection invalidates the enumerator when it next calls MoveNext.

You can enumerate the Keys or AllKeys (which is just a string array) and modify the values they point to quite safely.

Also, the properties of KeyValuePair<K, V> are themselves read-only, so, iterator blocks or not, there's no circumstances under which you could modify those values without abusing reflection.

Quick Joe Smith
serhio: the reason you cannot modify the dictionary that way is because you also modify the values that are enumerated over. Using the Keys as Quick Joe Smith recommends above will allow you to modify the values - but do not try to add/remove keys while in your foreach loop this way.
mattdekrey
Thanks for highlighting that. It's worth realising that most collection classes in .NET are made up of multiple individual collections.
Quick Joe Smith
I need to take care of the order of entries. Say i added keys 1, 10, 3, 5, I need to modify it in the same order: 1, 10, 3, 5. Will this order be respected?
serhio
I think that will depend on the type of collection you are using. Most dictionaries store their keys in hash order (which is unpredictable), but there is an ordered dictionary class that preserves the order in which items are added. From a bit of testing I did, the generic Dictionary<K, V> preserves insertion order too.
Quick Joe Smith