Changing values in a Dictionary class






3.75/5 (4 votes)
If you try to enumerate through a Dictionary's key collection and attempt to change the values as in the code below, Dictionary _items = new Dictionary();...int i = 0;//Attempt to set the values for this Dictionary item.foreach (string key in...
If you try to enumerate through a Dictionary's key collection and attempt to change the values as in the code below,
Dictionary<string, string> _items = new Dictionary<string, string>(); ... int i = 0; //Attempt to set the values for this Dictionary item. foreach (string key in _items.Keys) { _items[key] = elements[i++]; }you will get the following error:
System.InvalidOperationException was unhandled Message="Collection was modified; enumeration operation may not execute."You would think that if you are not changing the keys, then you will not foul up the enumerator, but you'd be wrong. The solution is to copy out the key collection and iterate through that.
int i = 0; //Copy out the key collection as an array. string [] keys = _items.Keys.ToArray<string>(); //Do not use a foreach loop for (i = 0; i < keys.Length; i++) { _items[keys[i]] = elements[i]; }