It is still deleted from the collection based on the where () linq clause (.RemoveWhere ()?)

I see that the collection has a .Remove () and .RemoveAt () method. I would like to do something like this:

  myObject.ChildList.RemoveWhere(r=>r.Name == "Joe");

What is the best way to achieve this, besides a separate one, where and then loop through each element and call them .Remove ()

+5
source share
3 answers

List<T>has a method RemoveAllthat takes a predicate.

myObject.ChildList.RemoveAll(r => r.Name == "Joe");
+13
source

You can write RemoveWhere()as an extension method. But changing collections is difficult and sometimes very inefficient.

Why not create a new collection?

myObject.ChildList = myObject.ChildList.Except(
      myObject.ChildList.Where(r=>r.Name == "Joe"));
+2
source

Depending on how much you need your conditions, you can just call Where (), but invert all the logic you would do in RemoveWhere (). This can be a bit confusing and will almost certainly be slightly less efficient than a function like RemoveWhere (), but if you want to do something simple and lazy, everything will be fine.

0
source

All Articles