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

前端 未结 11 734
不思量自难忘°
不思量自难忘° 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 05:59

    The collection used in foreach is immutable. This is very much by design.

    As it says on MSDN:

    The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.

    The post in the link provided by Poko indicates that this is allowed in the new concurrent collections.

提交回复
热议问题