Reputation: 18308
foreach (string key in dbFields.Keys)
dbFields[key] = MySqlHelper.EscapeString(dbFields[key]);
I get an InvalidOperationException error claiming the collection has been modified. Why does it think the Keys collection has been modified?
I just want to apply the function to all of the values of the dictionary -_-
I know I can do this if I use a second dictionary. I was just wondering if there is a tight simplistic elegant way to modify all values in a dictionary (without explicitly creating a second one).
Upvotes: 2
Views: 2468
Reputation: 160952
Try this:
foreach (string key in dbFields.Keys.ToList())
dbFields[key] = MySqlHelper.EscapeString(dbFields[key]);
You cannot modify the collection you are iterating over, ToList()
in this case will create a new List<string>
for you that you are iterating over, so you can safely modify the dictionary.
In regards to the comment - from MSDN:
The Dictionary.KeyCollection is not a static copy; instead, the Dictionary.KeyCollection refers back to the keys in the original Dictionary. Therefore, changes to the Dictionary continue to be reflected in the Dictionary.KeyCollection.
So it depends on the implementation of the indexer (dbFields[key] = ...
) if the Dictionary considers the key collection changed (obviously it does since there's an exception) - unfortunately I don't have Reflector handy at the moment otherwise I could just check.
Upvotes: 7