.NET - Remove from a List<T> within a 'foreach' loop
Solution 1:
You can iterate through the list backwards:
for (int i = myList.Count - 1; i >= 0; i--)
{
if (whatever) myList.RemoveAt(i);
}
In response to your comment about wanting to quit when you find an item that you're NOT removing, then just using a while loop would be the best solution.
Solution 2:
You should never remove anything from a collection you are iterating over while inside of a foreach loop. It's basically like sawing the branch you are sitting on.
Use your while alternative. It is the way to go.
Solution 3:
Do you really need to do this within a foreach
loop?
This will achieve the same results as your examples, ie, remove all items from the list up until the first item that matches the condition (or remove all items if none of them match the condition).
int index = Os.FindIndex(x => x.cond);
if (index > 0)
Os.RemoveRange(0, index);
else if (index == -1)
Os.Clear();