Home >Backend Development >C++ >How to Safely Remove Elements from a List While Iterating in C#?

How to Safely Remove Elements from a List While Iterating in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-31 02:08:11592browse

How to Safely Remove Elements from a List While Iterating in C#?

Remove the list element safely when iterates 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.

Use for loop reverse iteration

One method is to use the for loop reverse iteration list. This can prevent the index position of destroying the collection:

Removeall method

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

Statement:
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