gpt4 book ai didi

c# - 在 foreach 循环中编辑字典值

转载 作者:IT王子 更新时间:2023-10-29 03:30:21 26 4
gpt4 key购买 nike

我正在尝试根据字典构建饼图。在显示饼图之前,我想整理一下数据。我正在删除任何小于 5% 的馅饼切片,并将它们放入“其他”馅饼切片中。但是我得到一个 Collection was modified;枚举操作可能不会在运行时执行异常。

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

最佳答案

在字典中设置一个值会更新其内部“版本号”——这会使迭代器以及与键或值集合关联的任何迭代器无效。

我明白你的意思,但与此同时,如果值集合可以在迭代中更改,那将很奇怪 - 为简单起见,只有一个版本号。

解决此类问题的正常方法是预先复制键集合并迭代副本,或者迭代原始集合但保留一组更改,您将在完成迭代后应用这些更改.

例如:

先复制 key

List<string> keys = new List<string>(colStates.Keys);
foreach(string key in keys)
{
double percent = colStates[key] / TotalCount;
if (percent < 0.05)
{
OtherCount += colStates[key];
colStates[key] = 0;
}
}

或者...

创建修改列表

List<string> keysToNuke = new List<string>();
foreach(string key in colStates.Keys)
{
double percent = colStates[key] / TotalCount;
if (percent < 0.05)
{
OtherCount += colStates[key];
keysToNuke.Add(key);
}
}
foreach (string key in keysToNuke)
{
colStates[key] = 0;
}

关于c# - 在 foreach 循环中编辑字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1070766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com