Sometimes you’re going to find that you need to iterate over a collection like a List and make some modification while you’re in there.
It might look like this:
foreach (var item in list) if (item.Name == "Chris") list.Remove(item);
Seems easy enough, right? But doing this is going to give you a compiler error:
System.InvalidOperationException: Collection was modified; enumeration operation may not execute
So the question is, how do we get the same effect without getting the error? The trick is to copy the collection first.
var newList = List(sourceList); foreach (var item in sourceList) if (item == "Chris") newList.Remove(item); sourceList = newList;
Now there’s no longer an issue because the modification is done to the result collection and the collection being iterated over is never modified.