Home >Backend Development >C++ >How to Safely Remove Elements from a List While Iterating in C#?
Modifying the list during the iteration may cause problems, such as a headache that the "collection has been modified; the enumeration operation may not be executed" abnormal. However, some technologies can effectively remove elements during iteration.
One method is to use the for loop reverse iteration list. This can prevent the index position of destroying the collection:
<code class="language-csharp">for (int i = safePendingList.Count - 1; i >= 0; i--) { // 处理元素 // safePendingList.RemoveAt(i); }</code>
Another choice is to use the Removeall method with predicate to check each element:
Example
<code class="language-csharp">safePendingList.RemoveAll(item => item.Value == someValue);</code>Consider the following integer list:
Before removal:
<code class="language-csharp">var list = new List<int>(Enumerable.Range(1, 10));</code>Output:
After removal:
<code class="language-csharp">Console.WriteLine("移除前:"); list.ForEach(i => Console.WriteLine(i));</code>
Output:
<code>1 2 3 4 5 6 7 8 9 10</code>This demonstrates how to remove elements greater than 5 from the list.
The above is the detailed content of How to Safely Remove Elements from a List While Iterating in C#?. For more information, please follow other related articles on the PHP Chinese website!