我正试图从字典中建立一个饼图。在显示饼图之前,我想整理一下数据。我去掉了所有小于5%的派片,把它们放到“其他”派片里。然而,我得到一个集合被修改;枚举操作在运行时不能执行异常。

我理解为什么在遍历字典时不能从字典中添加或删除项。但是,我不明白为什么不能简单地在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);

当前回答

在ForEach中不能直接修改键或值,但可以修改它们的成员。例如,这应该工作:

public class State {
    public int Value;
}

...

Dictionary<string, State> colStates = new Dictionary<string,State>();

int OtherCount = 0;
foreach(string key in colStates.Keys)
{
    double  Percent = colStates[key].Value / TotalCount;

    if (Percent < 0.05)
    {
        OtherCount += colStates[key].Value;
        colStates[key].Value = 0;
    }
}

colStates.Add("Other", new State { Value =  OtherCount } );

其他回答

在foreach循环中调用ToList()。这样我们就不需要一个临时变量的拷贝。它依赖于自。net 3.5以来可用的Linq。

using System.Linq;

foreach(string key in colStates.Keys.ToList())
{
  double  Percent = colStates[key] / TotalCount;

    if (Percent < 0.05)
    {
        OtherCount += colStates[key];
        colStates[key] = 0;
    }
}

你可以把字典做一个列表副本。值,然后您可以使用列表。ForEach lambda函数用于迭代(或如前所述的ForEach循环)。

new List<string>(myDict.Values).ForEach(str =>
{
  //Use str in any other way you need here.
  Console.WriteLine(str);
});

你在这一行修改集合:

col各州[键]= 0;

通过这样做,您实际上是在此时删除和重新插入一些内容(就IEnumerable而言)。

如果你编辑你存储的值的一个成员,那是可以的,但是你在编辑值本身,而IEnumberable不喜欢这样。

我使用的解决方案是消除foreach循环,只使用for循环。 简单的for循环不会检查您知道不会影响集合的更改。

你可以这样做:

List<string> keys = new List<string>(colStates.Keys);
for(int i = 0; i < keys.Count; i++)
{
    string key = keys[i];
    double  Percent = colStates[key] / TotalCount;
    if (Percent < 0.05)    
    {        
        OtherCount += colStates[key];
        colStates[key] = 0;    
    }
}

与其他答案一起,我想我应该注意一下,如果您获得sortedDictionary。Keys或sortedDictionary。值,然后用foreach遍历它们,你也会按顺序遍历。这是因为这些方法返回System.Collections.Generic.SortedDictionary<TKey,TValue>。KeyCollection或SortedDictionary<TKey,TValue>。ValueCollection对象,它维护原始字典的排序。

如果你觉得有创意,你可以这样做。在字典中进行反向循环以进行更改。

Dictionary<string, int> collection = new Dictionary<string, int>();
collection.Add("value1", 9);
collection.Add("value2", 7);
collection.Add("value3", 5);
collection.Add("value4", 3);
collection.Add("value5", 1);

for (int i = collection.Keys.Count; i-- > 0; ) {
    if (collection.Values.ElementAt(i) < 5) {
        collection.Remove(collection.Keys.ElementAt(i)); ;
    }

}

当然不完全相同,但你可能会感兴趣…