Home > Backend Development > C++ > Should I Use a `foreach` or `for` Loop to Modify Lists in C#?

Should I Use a `foreach` or `for` Loop to Modify Lists in C#?

DDD
Release: 2025-01-27 13:41:09
Original
861 people have browsed it

Should I Use a `foreach` or `for` Loop to Modify Lists in C#?

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

The

foreach 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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template