我正在尝试从字典中构建饼图.在我显示饼图之前,我想整理数据.我正在删除任何小于饼的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) 为什么foreach循环只读?我的意思是你可以获取数据,但不能增加++或减少 - .它背后的任何原因?是的我是初学者:)
〔实施例:
int[] myArray={1,2,3};
foreach (int num in myArray)
{
num+=1;
}
Run Code Online (Sandbox Code Playgroud)