Editing dictionary values in a foreach loop

I am trying to build a pie chart from a dictionary. Before I display the pie chart, I want to tidy up the data. I’m removing any pie slices that would be less than 5% of the pie and putting them in a “Other” pie slice. However I’m getting a Collection was modified; enumeration operation may not execute exception at runtime.

I understand why you can not add or remove items from a dictionary while iterating over them. However I don’t understand why you can’t simply change a value for an existing key within the foreach loop.

Any suggestions re: fixing my code, would be appreciated.

Dictionary<string, int> colStates = new Dictionary<string,int>();
// ...
// Some code to populate colStates dictionary
// ...

int OtherCount = 0;

foreach(string key in colStates.Keys)
{

    double  Percent = colStates[key] / TotalCount;

    if (Percent < 0.05)
    {
        OtherCount += colStates[key];
        colStates[key] = 0;
    }
}

colStates.Add("Other", OtherCount);

14 Answers
14

Leave a Comment