我正在尝试从一个字典中构建饼图。在显示饼图之前,我希望清理数据。我正在删除任何小于饼图总量5%的扇区,并将它们放入“其他”扇区。但是运行时我遇到了Collection was modified; enumeration operation may not execute
异常。
我理解为什么不能在迭代过程中添加或删除字典中的项。但是我不明白为什么不能在foreach循环中仅更改现有键的值。
欢迎任何关于修复我的代码的建议。
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);