Click here to Skip to main content
Click here to Skip to main content

Tagged as

Changing values in a Dictionary class

, 6 May 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Gordon Kushner
Software Developer (Senior)
United States United States
No Biography provided

Comments and Discussions

 
GeneralForeach PinmemberAdam Robinson15-Dec-09 8:08 
GeneralRe: Foreach Pinmembergkushner15-Dec-09 8:11 
GeneralRe: Foreach PinmemberAdam Robinson15-Dec-09 8:14 
GeneralRe: Foreach Pinmembergkushner15-Dec-09 8:50 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.141015.1 | Last Updated 6 May 2010
Article Copyright 2009 by Gordon Kushner
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid