.netforeachremove-method

.NET - Remove from a List<T> within a 'foreach' loop


I have code that I want to look like this:

List<Type> Os;

...

foreach (Type o in Os)
    if (o.cond)
        return;  // Quitting early is important for my case!
    else
        Os.Remove(o);

... // Other code

This doesn't work, because you cannot remove from the list when you are inside a foreach loop over that list:

Is there a common way to solve the problem?

I can switch to a different type if needed.

Option 2:

List<Type> Os;

...

while (Os.Count != 0)
     if (Os[0].cond)
         return;
     else
         Os.RemoveAt(0);

... // Other code

Ugly, but it should work.


Solution

  • 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();