我正在尝试从字典中构建饼图.在我显示饼图之前,我想整理数据.我正在删除任何小于饼的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);
Run Code Online (Sandbox Code Playgroud) 经过几个小时的研究(在MSDN网站等),我没有找到为什么通用Dictionary<TKey, TValue>
不提供ForEach()
像List<T>
这样的方法.有人可以给我一个解释吗?(我知道将它作为扩展方法实现并不难,这里可以看到一个很好的例子,我只是想知道为什么它首先不是由.NET库提供的特定原因.)
提前致谢.