Home > Backend Development > C++ > How to Safely Add Items to a List While Iterating with a Foreach Loop in C#?

How to Safely Add Items to a List While Iterating with a Foreach Loop in C#?

Susan Sarandon
Release: 2025-01-27 13:31:12
Original
389 people have browsed it

How to Safely Add Items to a List While Iterating with a Foreach Loop in C#?

Modify the list in the Foreach loop in C#

In the C# version before 4.0, trying to modify the list in the Foreach cycle will cause abnormalities. However, in the .NET 4.0, this limit was canceled.

Question:

Given the following code, when using FOREACH to iterate its nested Enumeration, what is the best way to add projects to the project list?

Best Practice:

<code class="language-csharp">foreach (var item in Enumerable)
{
    foreach (var item2 in item.Enumerable)
    {
        item.Add(new item2); // 这行代码有问题
    }
}</code>
Copy after login

The set used in the Foreach loop is unable to be designed. Therefore, it cannot be modified directly during iteration. In order to modify the list safely, it is recommended to use the traditional for loop. Explanation:

MSDN document points out that the Foreach statement is used for iterative collection. Although it does not hide or delete items to the source collection, it also warns not to rely on this behavior because there are potential side effects. If you need to modify the source collection, the recommended method is to use for loop.

The concurrent collection is abnormal:

The Paul Jackson blog article quoted in the problem states that the set is allowed in the C# concurrent collection. This exception is derived from the setting of the concurrent collection, and it handles potential side effects in different ways. Therefore, this rule is not suitable for concurrent collection. For ordinary sets, it is still recommended to use the

cycle to avoid potential problems.

The above is the detailed content of How to Safely Add Items to a List While Iterating with a Foreach Loop 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template