Changing collection inside foreach

2020-04-28 04:42发布

Here is my code:

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

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 says that "The collection was modified". sorry can't provide real message of exception because it in non-english

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

标签: c# linq
3条回答
forever°为你锁心
2楼-- · 2020-04-28 05:31

This is what I do, when I need to modify the collection.

foreach (OrderItem item in OrderInfo.order.ToList())
{
     ...
}

Create a copy. Enumerate the copy, but update the original one.

查看更多
看我几分像从前
3楼-- · 2020-04-28 05:43

You can use an extension ToEach static method:

public delegate void ToEachTransformAction<T>(ref T Telement);

[Extension()]
public static void ToEach<T>(Generic.IList<T> thislist, ToEachTransformAction<T> Transform)
    {
        for (var n = 0; n < thislist.Count; n++)
        {
            Transform.Invoke(thislist(n));
        }
    }
查看更多
甜甜的少女心
4楼-- · 2020-04-28 05:44

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;
}

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.

查看更多
登录 后发表回答