2

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

void
  • 718
  • 7
  • 21

3 Answers3

8

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.

Shani Elharrar
  • 667
  • 4
  • 5
  • 2
    Are you sure can this helped? Where are you see `odrer` collection changes? – Hamlet Hakobyan Jan 19 '13 at 09:59
  • @HamletHakobyan possibly, it is a side-effect in the `Value` setter -- we can't know without seeing the code. However, this is the solution for the enumerator invalidation problem. The `for` loop will solve that problem for sure. – Eren Ersönmez Jan 19 '13 at 10:04
  • @acrilige you don't know that. He may be changing the collection the `Value` setter. You can't know without seeing the full code. – Eren Ersönmez Jan 19 '13 at 10:09
2

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.

Ondra
  • 1,619
  • 13
  • 27
0

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));
        }
    }
anefeletos
  • 672
  • 7
  • 19