During the iterative process, the element of the generic list is safely removed
In many programming scenarios, the elements in the list need to be processed. However, if certain elements need to be removed during this process, the standard method may have problems.
The use of
in the cycle will cause abnormalities, and the decreasing counter and use will destroy the current set position. foreach
.Remove(element)
A more elegant solution is the list of reverse iterations: .RemoveAt(i)
This ensures that the removal element does not affect the current position in the list.
<code class="language-csharp">for (int i = safePendingList.Count - 1; i >= 0; i--) { // 处理元素 // 如需移除元素 // safePendingList.RemoveAt(i); }</code>
The following example demonstrates the use of RemoveAll
cycle method:
<code class="language-csharp">safePendingList.RemoveAll(item => item.Value == someValue);</code>
Output:
for
The above is the detailed content of How to Safely Remove Elements from a Generic List While Iterating?. For more information, please follow other related articles on the PHP Chinese website!