void
void

Reputation: 718

Changing collection inside foreach

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

Upvotes: 2

Views: 5615

Answers (3)

anefeletos
anefeletos

Reputation: 702

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

Upvotes: 0

Ondra
Ondra

Reputation: 1647

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.

Upvotes: 2

Shani Elharrar
Shani Elharrar

Reputation: 657

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.

Upvotes: 8

Related Questions