我正在尝试从字典中构建饼图。在展示饼图之前,我想整理一下数据。我将删除所有饼图片的比例不到5%,然后放入“其他”饼图片。但是,我在运行时遇到了Collection was modified; enumeration operation may not execute
异常。在foreach循环中编辑字典值
我明白为什么在迭代它们的时候不能在字典中添加或删除项目。不过,我不明白为什么你不能简单地改变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);
我知道这是旧的,但如果使用.NET 3.5(或是4.0?),您可以使用和滥用LINQ如下: foreach(string key in colStates.Keys.ToList()){...} – Machtyn 2015-03-16 20:57:51
@Machtyn:当然 - 但问题是关于.NET 2.0,否则我肯定*会使用LINQ。 – 2015-03-16 21:10:25