【发布时间】:2009-07-01 19:00:50
【问题描述】:
我正在尝试从字典构建饼图。在显示饼图之前,我想整理一下数据。我正在删除任何小于 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);
【问题讨论】:
-
在 .NET5 中可以。 stackoverflow.com/questions/66939923/…