相关疑难解决方法(0)

在foreach循环中编辑字典值

我正在尝试从字典中构建饼图.在我显示饼图之前,我想整理数据.我正在删除任何小于饼的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)

.net c# .net-2.0

180
推荐指数
5
解决办法
12万
查看次数

为什么.NET中的通用字典不提供ForEach()方法?

经过几个小时的研究(在MSDN网站等),我没有找到为什么通用Dictionary<TKey, TValue>不提供ForEach()List<T>这样的方法.有人可以给我一个解释吗?(我知道将它作为扩展方法实现并不难,这里可以看到一个很好的例子,我只是想知道为什么它首先不是由.NET库提供的特定原因.)

提前致谢.

c# generics iteration foreach dictionary

1
推荐指数
1
解决办法
108
查看次数

标签 统计

c# ×2

.net ×1

.net-2.0 ×1

dictionary ×1

foreach ×1

generics ×1

iteration ×1