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
Release: 2025-01-31 02:08:11
Original
594 people have browsed it

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

for (int i = safePendingList.Count - 1; i >= 0; i--)
{
    // 处理元素
    // safePendingList.RemoveAt(i);
}
Copy after login

Another choice is to use the Removeall method with predicate to check each element:

<示> Example

safePendingList.RemoveAll(item => item.Value == someValue);
Copy after login
Consider the following integer list:

<除> Before removal:

var list = new List<int>(Enumerable.Range(1, 10));
Copy after login
Output: <<>

<除> After removal:

Console.WriteLine("移除前:");
list.ForEach(i => Console.WriteLine(i));
Copy after login

Output: <<>

<code>1
2
3
4
5
6
7
8
9
10</code>
Copy after login
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 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