1

I can't figure out why this works:

var list = new List<int>() { 1, 4, 3, 2, 0, 1 };

foreach (var item in list.ToList())
{
    if (item == 1)
    {
        list.Remove(item);
    }
}

...and this doesn't:

var list = new List<int>() { 1, 4, 3, 2, 0, 1 };

foreach (var item in list)
{
    if (item == 1)
    {
        list.Remove(item);
    }
}

If you run the second snippet, it'll give you the following error:

Collection was modified; enumeration operation may not execute.

Per documentation, the enumeration only remains valid if it's unchanged. What I don't get is how I'm able to get around it with the first code snippet? Could someone break it down for me?

B.K.
  • 9,982
  • 10
  • 73
  • 105
  • 2
    In the first example you are enumerating a 'copy' of the list and removing items from the original list. In the second, your are enumerating the original list and trying to remove items from the original –  May 19 '14 at 02:39
  • @StephenMuecke Oh my... do I feel silly. You're absolutely right. – B.K. May 19 '14 at 02:42
  • Side note: If you've searched for the "Collection was modified; enumeration operation may not execute." you'd immediately find [SO answer](http://stackoverflow.com/questions/604831/collection-was-modified-enumeration-operation-may-not-execute) that shows exactly your code as workaround. – Alexei Levenkov May 19 '14 at 02:47
  • @AlexeiLevenkov I've seen several of them, but didn't see that one. The ones I saw didn't answer my question. My search parameters were a bit different, so that could be the cause. – B.K. May 19 '14 at 02:48

2 Answers2

4

Because in the first code snippet you are not iterating over your list, you are iterating over the copy of your list.

So removing an item from original list doesn't cause any exception because it is different from the collection that is being enumerated.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
4

Because .ToList() isn't a casting operation, it makes a copy of your original list.

So you are then iterating over the copy and modifying the original.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • You're right, I can't believe I didn't realize that. All the time I had myself thinking, for some reason, that I'm casting and assigning. What a silly mistake to make. – B.K. May 19 '14 at 02:43