在foreach内部更改集合 [英] Changing collection inside foreach

查看:158
本文介绍了在foreach内部更改集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

foreach (OrderItem item in OrderInfo.order)
{
     orderItemViews.Single(i => i.numericUpDown.Name == item.id.ToString()).numericUpDown.Value = item.count;
}

它给出了一个例外.
我知道我无法在 foreach
中更改集合 如何更改此代码以使其正常工作?最好的是LINQ代码.

It gives an exception.
I know that I can't change the collection inside foreach
How can I change this code to make it work? Best of all if it would be LINQ code.

exception表示集合已修改".抱歉无法提供真正的异常信息,因为它是非英语的

exception says that "The collection was modified". sorry can't provide real message of exception because it in non-english

对不起.我发现集合在改变.它位于* numericUpDown_ValueChanged *处理程序中.无论如何,我有一个答案.谢谢

sorry guys. I've found where collection is changing. It was inside *numericUpDown_ValueChanged* handler. anyway I've got an answer. thank you

推荐答案

您可以使用ToList(),如下所示:

You can use ToList(), Like this :

foreach (OrderItem item in OrderInfo.order.ToList())
{
     orderItemViews.Single(i => i.numericUpDown.Name == item.id.ToString()).numericUpDown.Value = item.count;
}

或使用普通的for循环:

Or use normal for loop :

for (int i = 0 ; i < OrderInfo.order.Count; i++)
{
     OrderItem item = OrderInfo.order[i];
     orderItemViews.Single(i => i.numericUpDown.Name == item.id.ToString()).numericUpDown.Value = item.count;
}

提示:出于性能考虑,最好使用第二种方法.

Tip : Performance wise, It's better to use the second way.

这篇关于在foreach内部更改集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆