Caleb Jares
Caleb Jares

Reputation: 6307

Modifying Values in a For Each Loop - Any Way?

I know this goes against the .NET rules, but sometimes I need it. For example, I need to run through a Dictionary<string, bool>. This dictionary stores my variables in a parsed logic equation. I want to output a truth table, so I need to iterate through and set elements.

One thing I've tried is

        foreach (var x in Variables.Keys)
        {
            bool on = ((in) & (j << in)) > 0;
            Variables[x] = on;
            builder.Append(on == true ? '1' : '0').Append('\t');
            j++;
        }

I just get a InvalidOperationException: Collection was modified; enumeration operation may not execute. I converted the dictionary to an array and tried to modify it that way, but KeyValuePair.Value is readonly, so it won't work.

Upvotes: 1

Views: 134

Answers (3)

themaninthesuitcase
themaninthesuitcase

Reputation: 4781

I create a copy of the collection first, then I'd iterate over the copy allowing me to mess with the original as required.

Upvotes: 0

Andrey Sergeev
Andrey Sergeev

Reputation: 1

You cannot edit Dictionary<TKey, TValue> in loop.

Try this:

var resultVariables = new Dictionary<string, bool>(Variables.Count);

foreach (var x in Variables.Keys)
{
     bool on = ((in) & (j << in)) > 0;
     resultVariables[x] = on;
     builder.Append(on == true ? '1' : '0').Append('\t');
     j++;
}

Variables = resultVariables;

Upvotes: 0

ChaosPandion
ChaosPandion

Reputation: 78262

You could create a copy of the key collection:

foreach (var x in Variables.Keys.ToArray())

Upvotes: 9

Related Questions