如何在迭代字典项时更新值?
我有一本字典:
Dictionary<string, long> Reps = new Dictionary<string, long>();
我想在迭代所有项目时更新值,如下所示:
foreach (string key in Reps.keys)
{
Reps[key] = 0;
}
它给我一个错误说:
"Collection was modified; enumeration operation may not execute"
任何人都可以告诉我为什么它给我这个错误,因为我还有一个函数添加了value,并且在单击按钮时调用:
public static void Increment(string RepId, int amount)
{
long _value = Convert.ToInt64(Reps[RepId]);
_value = _value + amount;
Reps[RepId] = _value;
}
并且该函数工作正常。那么更新所有值时出现什么问题呢?解决方案是什么?
I have a dictionary:
Dictionary<string, long> Reps = new Dictionary<string, long>();
and I want to update the values while iterating through all items, like this:
foreach (string key in Reps.keys)
{
Reps[key] = 0;
}
it is giving me an error saying:
"Collection was modified; enumeration operation may not execute"
can anyone tell me why it is giving me this error, because I have one more function that adds the value, and it is called when button is clicked:
public static void Increment(string RepId, int amount)
{
long _value = Convert.ToInt64(Reps[RepId]);
_value = _value + amount;
Reps[RepId] = _value;
}
and this function is working fine. so whats the problem when updating all the values? And whats the solution for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更简单的是,这样做:
错误的原因是您正在尝试编辑正在使用的实际对象,如果您复制它然后像这样使用它:
它也会给出相同的错误指向原始对象,当添加 ToList() 时,它创建了一个新的 List 对象
more simplified, do this:
and the reason for the error is you are trying to edit the actual object which is in use and if you make a copy of it and then use it like this:
it'll give the same error as it also pointing to the original object, and when the ToList() is added it created a new object of List
问题是没有更新值,您只是无法在迭代 foreach 时更改 foreach() 所基于的集合。
尝试这样的事情,
这会起作用。
The problem is no updating the values, you just cannot change the collection that your foreach() is based on while the foreach is being iterated.
Try somehting like this
this would work.
发生这种情况是因为您在使用
foreach
循环时更改了Dictionary
中的元素。试试这个。现在您正在循环遍历根据字典键创建的列表。由于修改的不是原始集合,因此错误将会消失。
This happens because you are changing the element in the
Dictionary<string, long>
while looping over it withforeach
. Try this.Now you are looping over a list created from the dictionarys key. As it is not the original collection thats modified, the error will go away.