我正在嘗試從字典中構建餅圖。在展示餅圖之前,我想整理一下數據。我將刪除所有餅圖片的比例不到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