The best practice of removing elements from the generic list safely and efficiently
When the iterative generic list and execute the operation that may need to remove the element, it is important to choose the appropriate iteration mode to avoid common traps. For example, the use of
in the cycle will cause abnormalities, because the collection is modified during the enumeration process.
foreach
Steady solution .Remove(element)
In order to solve this problem, it is recommended to use the cyclic reverse iteration list. This method ensures that the current position in the set when removing elements is accurate.
Example: for
<code class="language-csharp">for (int i = safePendingList.Count - 1; i >= 0; i--) { // 处理元素 // safependingList.RemoveAt(i); }</code>
Alternative method
Another choice is to use<code class="language-csharp">var list = new List<int>(Enumerable.Range(1, 10)); for (int i = list.Count - 1; i >= 0; i--) { if (list[i] > 5) list.RemoveAt(i); } list.ForEach(i => Console.WriteLine(i));</code>
Simplified demonstration:
RemoveAll
<code class="language-csharp">safePendingList.RemoveAll(item => item.Value == someValue);</code>
The above is the detailed content of How to Safely and Efficiently Remove Elements from a Generic List While Iterating?. For more information, please follow other related articles on the PHP Chinese website!