What is the best way to modify a list in a 'foreach' loop?

前端 未结 11 751
不思量自难忘°
不思量自难忘° 2020-11-22 05:23

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

11条回答
  •  灰色年华
    2020-11-22 06:17

    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.

提交回复
热议问题