Click here to Skip to main content
15,891,033 members
Articles / .NET
Tip/Trick

Changing values in a Dictionary class

Rate me:
Please Sign up or sign in to vote.
3.75/5 (4 votes)
6 May 2010CPOL 28.1K   3   4
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];
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralForeach Pin
Adam Robinson15-Dec-09 8:08
Adam Robinson15-Dec-09 8:08 
GeneralRe: Foreach Pin
Gordon Kushner15-Dec-09 8:11
Gordon Kushner15-Dec-09 8:11 
GeneralRe: Foreach Pin
Adam Robinson15-Dec-09 8:14
Adam Robinson15-Dec-09 8:14 
GeneralRe: Foreach Pin
Gordon Kushner15-Dec-09 8:50
Gordon Kushner15-Dec-09 8:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.