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?