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:
for (int i = safePendingList.Count - 1; i >= 0; i--) { // 处理元素 // safePendingList.RemoveAt(i); }
Another choice is to use the Removeall method with predicate to check each element:
<示> Example
safePendingList.RemoveAll(item => item.Value == someValue);
<除> Before removal:
var list = new List<int>(Enumerable.Range(1, 10));
<除> After removal:
Console.WriteLine("移除前:"); list.ForEach(i => Console.WriteLine(i));
Output: <<>
<code>1 2 3 4 5 6 7 8 9 10</code>
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!