Modify list in C#: foreach
loop or for
loop?
In versions prior to C# 4.0, modifying a list during a foreach
loop would cause an exception. However, .NET 4.0 introduced support for this feature. Still, the best approach is to use a traditional for
loop.
Immutable enum
Theforeach
statement uses immutable collections, as MSDN states: "The foreach
statement...cannot be used to add or remove items from the source collection to avoid unpredictable side effects."
for
Loop Solution
To modify a list while iterating it, it is recommended to switch to a for
loop:
<code class="language-csharp">for (var i = 0; i < list.Count; i++) { // 修改 list[i] }</code>
This approach allows iteration and modification without encountering bugs or unexpected behavior.
Concurrent collection exception
Please note that the blog referenced in the question mentions that this exception does not apply to concurrent collections introduced in .NET 4.0. However, it is still recommended to use a for
loop for list modification as it is the recommended and most reliable technique.
The above is the detailed content of Should I Use a `foreach` or `for` Loop to Modify Lists in C#?. For more information, please follow other related articles on the PHP Chinese website!