A new feature in C# / .NET 4.0 is that you can change your enumerable in a foreach
without getting the exception. See Paul Jackson\'s blog entry An Interest
You can't change the enumerable collection while it is being enumerated, so you will have to make your changes before or after enumerating.
The for
loop is a nice alternative, but if your IEnumerable
collection does not implement ICollection
, it is not possible.
Either:
1) Copy collection first. Enumerate the copied collection and change the original collection during the enumeration. (@tvanfosson)
or
2) Keep a list of changes and commit them after the enumeration.