我正在尝试从字典中构建饼图.在我显示饼图之前,我想整理数据.我正在删除任何小于饼的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) 编辑:我不觉得这是重复的 - 我没有清楚地说明我想知道一种有效的方法来填充字典值左边的字符.我标记为答案的问题应该澄清,因为它是一个非常不同的答案,而不是其他主题的答案.对不起,我措辞错了.
我试图验证我的词典中的所有值都是一定的长度,如果不是,请在左侧填充"0".我知道"问题是什么",我正在阅读字典的KVP,然后修改它当然会引发异常,但我不知道如何修改我的代码使其"合法"
class prefixMe
{
Dictionary<string, string> d = new Dictionary<string, string>();
public prefixMe()
{
d.Add("one", "123456");
d.Add("two", "678");
d.Add("three", "13");
foreach(KeyValuePair<string,string> k in d)
{
StringBuilder sb = new StringBuilder(k.Value);
while(sb.Length != 10)
{
Console.WriteLine("Key:{0}\tValue:{1}", k.Key, sb);
sb.Insert(0, '0');
}
d[k.Key] = sb.ToString();
//k.Value.Replace(k.Value, sb.ToString());// = sb.ToString();
Console.WriteLine("Key:{0}\tNew Value:{1}", k.Key, d[k.Key]);
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
休息; 停止代码抛出错误,但也使得它不会通过其他值,因为它突破了foreach循环.
结果应该是:
0000123456
0000000678
0000000013
Run Code Online (Sandbox Code Playgroud)