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>
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!