Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there anyway to remove from a collection based on a .Where() linq clause (.RemoveWhere() ?)

I see a collection has a .Remove() and a .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 doing a seperate where and then a loop through each item and them calling .Remove()

like image 673
leora Avatar asked Nov 07 '11 18:11

leora


People also ask

How to remove row in LINQ?

You can delete rows in a database by removing the corresponding LINQ to SQL objects from their table-related collection. LINQ to SQL translates your changes to the appropriate SQL DELETE commands.

What is any () in Linq?

The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.

How does select work in Linq?

LINQ Select operator is used to return an IEnumerable collection of items, including the data performed on the transformation of the method. By using Select Operator, we can shape the data as per our needs. In it, we can use two syntax types; let's see each method working flow.


2 Answers

List<T> has a RemoveAll method that accepts a predicate.

myObject.ChildList.RemoveAll(r => r.Name == "Joe");
like image 73
Anthony Pegram Avatar answered Nov 15 '22 20:11

Anthony Pegram


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

Why not create a new collection?

myObject.ChildList = myObject.ChildList.Except(
      myObject.ChildList.Where(r=>r.Name == "Joe"));
like image 23
Henk Holterman Avatar answered Nov 15 '22 20:11

Henk Holterman