0

I have a collection lets say list of integers and looping through it using foreach, but if I have to insert data into the list during the loop, how do I do that ? I'm getting

Unhandled Exception: System.InvalidOperationException: Collection was modified enumeration operation may not execute.

This is the sample code below. I thought AsReadonly() would return a collection that was prior to modified state. That is not the case here.

ints = new List<int>(30);
ints.AddRange(Enumerable.Range(1, 10));
int y = 11;

foreach(int x in ints.AsReadOnly())
{
    ints.Add(y++);
    Console.WriteLine(x);
}
Suman Banerjee
  • 1,923
  • 4
  • 24
  • 40
Jagannath
  • 3,995
  • 26
  • 30
  • 3
    out of curiosity? what does the snipped above do? I am asking because it is not even possible to suggest you an alternative approach without understanding what is your real use case. – Davide Piras Sep 11 '11 at 15:54
  • possible duplicate of [How to modify or delete items from an enumerable collection while iterating through it in C#](http://stackoverflow.com/questions/308466/how-to-modify-or-delete-items-from-an-enumerable-collection-while-iterating-throu) – adrianbanks Sep 11 '11 at 16:07

5 Answers5

2

You need to use a copy of the list that can't be modified. This works:

foreach(int x in ints.ToArray())
{
    ints.Add(y++);
    Console.WriteLine(x);
}

The copy is unpleasant of course. In this particular case, since you are only adding elements, you can avoid the copy by using a for() loop:

int count = ints.Count;
for (int ix = 0; ix < count; ++ix) {
    ints.Add(y++);
    Console.WriteLine(ints[ix]);
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
1

As the documentation states AsReadonly() is only a wrapper on the original collection so you are still operating on the same collection - the same rules apply.

A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
1

As others mentioned AsReadonly() only produces a wrapper around the original list.

Something like this would work. But I am not sure what you are trying to do so it might not be helpful.

var ints = new List<int>();
ints.AddRange(Enumerable.Range(1, 10));
int y = 11;

var moreInts = new List<int>();

foreach(int x in ints.AsReadOnly())
{
    moreInts.Add(y++);
    Console.WriteLine(x);
}

ints.AddRange(moreInts);
Mike Two
  • 44,935
  • 9
  • 80
  • 96
0

You cant modify a collection while inside foreach loop. Try to use for-loop instead.

  • You can't modify the collection you are iterating on. But you can modify another collection, which makes the `ToArray()` approach Hans mentioned in a comment possible. – svick Sep 11 '11 at 16:26
0

The AsReadOnlyMethod() returns a wrapper list that prohibits modification, it is still the same list.

Mark Menchavez
  • 1,651
  • 12
  • 15