brian4342
brian4342

Reputation: 1253

Error using a dictionary in c#

I am trying to search through a dictionary to see if it has a certain value and if so then to change it. Here is my code:

foreach (var d in dictionary)
{
    if (d.Value == "red")
    {
         d.Value = "blue";
    }
}

In visual studio when i step through the code debugging it i can see it change the value then when it hits the foreach loop to reiterate again it throws an exception

"Collection was modified; enumeration operation may not execute"

How do i fix this?

Upvotes: 2

Views: 2601

Answers (6)

Y.Yanavichus
Y.Yanavichus

Reputation: 2417

var dict = new Dictionary<string, string>()
          {
                  { "first", "green" },
                  { "second", "red" },
                  { "third", "blue" }
          };

foreach (var key in dict.Keys.ToArray())
{
    if (dict[key] == "red")
    {
        dict[key] = "blue";
    }
}

Upvotes: 1

Botz3000
Botz3000

Reputation: 39610

If you want to replace all occurences of "red", you'll need to store the KeyValuePairs in a list or something like that:

var redEntries = dictionary.Where(e => e.Value == "red").ToList();
foreach (var entry in redEntries) {
    dictionary[entry.Key] = "blue";
}

Upvotes: 1

Yahya
Yahya

Reputation: 3444

Objects in foreach loops are read-only.

Please read through this and this for more understanding.

Upvotes: 0

Jeff
Jeff

Reputation: 2861

You cannot modify the collection you are iterating over in a foreach loop. If you could do that, it would open up several problems, such as "Do I run it on this newly-added value too?"

Instead, you should do something like this:

foreach( string key in dictionary.Keys )
{
    if( dictionary[key] == "red" )
    {
        dictionary[key] = "blue";
    }
}

Upvotes: 0

Mathew Thompson
Mathew Thompson

Reputation: 56429

You can't modify a collection whilst you're enumerating over it (in a loop).

You'll need to add your changes to a collection, then change them separately. Something like:

var itemsToChange = dictionary
    .Where(d => d.Value == "red")
    .ToDictionary(d => d.Key, d => d.Value);

foreach (var item in itemsToChange)
{
    dictionary[item.Key] = "blue";
}

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564413

You can't change it in the middle of the foreach - you'll need to come up with some other mechanism, such as:

// Get the KeyValuePair items to change in a separate collection (list)
var pairsToChange = dictionary.Where(d => d.Value == "red").ToList();
foreach(var kvp in pairsToChange)
    dictionary[kvp.Key] = "blue";

Upvotes: 6

Related Questions