You cannot change the value of a dictionary during a loop through elements in a dictionary, although you can change a property to a value if it is an instance of a reference type.
For example,
public class MyClass { public int SomeNumber { get; set;} } foreach(KeyValuePair<string, MyClass> entry in myDict) { entry.Value.SomeNumber = 3;
Attempting to modify a dictionary (or any collection) while passing through its elements will cause an InvalidOperationException report that the collection has been modified.
To answer your specific questions,
My question is, how can I change the value or key while passing through the dictionary?
The approach to both will be almost the same. You can either iterate over a copy of the dictionary, as Anthony Pengram said in his answer , or you can skip through all the elements once to find out which ones you need to change and then scroll through the list of these elements again:
List<string> keysToChange = new List<string>(); foreach(KeyValuePair<string, string> entry in myDict) { if(...)
And, can a dictionary allow a duplicate key? And if so, how can we avoid it?
The dictionary does not allow duplicate keys. If you need a collection of <string, string> pairs, run NameValueCollection .
Adam Lear Jun 29 '11 at 3:32 2011-06-29 03:32
source share