1

I have a List that i want to delete some members from. I want to use this kind of syntax :

List<Object> Foo = new List<Object>();

//Some code

foreach (Object obj in Foo)
    if (obj.ShouldBeDeleted())
        Foo.Remove(obj);

It felt wrong to iterate over a list and modify it at the same time, and a quick test confirmed it with an InvalidOperationException.

What is the correct way to selectively remove members of a list? I thought of using a copy of the list, and iterate over the copy while I delete from the original list, but it does not feel very memory efficient.

Sclrx
  • 151
  • 4
  • foreach Foo.ToList() to have a copy of the list. –  Oct 07 '19 at 14:02
  • 1
    @OlivierRogier That's the worst possible answer - keeping a list of items to remove isn't ideal, but it's cheaper than copying the entire source list. There are better answers in the suggested duplicate, like `RemoveAll` and iterating over the list backwards. – canton7 Oct 07 '19 at 14:03
  • 2
    You can either iterate by index in reverse, or make a new list `Foo.Where(f=>!f.ShouldBeDeleted()).ToList()` – spender Oct 07 '19 at 14:03
  • 3
    There already is a list member to do exactly what you want: [`List.RemoveAll()`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.removeall?view=netframework-4.8), which removes from the list all its elements that satisfy a predicate. – Matthew Watson Oct 07 '19 at 14:06
  • Did not see that it removes all, indeed @MatthewWatson. –  Oct 07 '19 at 15:16

0 Answers0