Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Change value of dictionary key-value pair while in foreach

I have this code which is being run every frame of a game:

    foreach (var repeaterAction in conditionTimes.Keys)
    {
        if (repeaterAction.Condition() == true)
        {
            if (conditionTimes[repeaterAction] == TimeSpan.Zero)
            {
                repeaterAction.Action();
            }
            else if (conditionTimes[repeaterAction] >= repeaterAction.InitialLapse)
            {
                repeaterAction.Action();
                conditionTimes[repeaterAction] -= repeaterAction.ActionInterval;
            }
            conditionTimes[repeaterAction] += gameTime.ElapsedGameTime;
        }
        else
        {
            conditionTimes[repeaterAction] = TimeSpan.Zero;
        }
    }

This is giving me the following error:

Collection was modified; enumeration operation may not execute.

Is there a way to modify the value in the key-value pair inside the foreach loop, without copying the Dictionary every frame?

like image 981
James Avatar asked Feb 23 '11 08:02

James


1 Answers

I'm Advising against trying to modify a collection while looping through it with dictionaries however it is possible since direct key access is available. Just add .ToArray() after the conditionTimes.Keys in the foreach then the keys becomes a separate collection and you can modify the dictionary:

foreach (var repeaterAction in conditionTimes.Keys.ToArray())
{
    if (repeaterAction.Condition() == true)
    {
        if (conditionTimes[repeaterAction] == TimeSpan.Zero)
        {
            repeaterAction.Action();
        }
        else if (conditionTimes[repeaterAction] >= repeaterAction.InitialLapse)
        {
            repeaterAction.Action();
            conditionTimes[repeaterAction] -= repeaterAction.ActionInterval;
        }
        conditionTimes[repeaterAction] += gameTime.ElapsedGameTime;
    }
    else
    {
        conditionTimes[repeaterAction] = TimeSpan.Zero;
    }
}

You also have to modify you're code so that if the key changes you actually remove an entry from your dictionary and add the new one, because keys really cant be changed, just removed.
Again this is not recommended.

like image 120
ntziolis Avatar answered Oct 27 '22 06:10

ntziolis