Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq remove item from object array where property equals value

If i have

IEnumberable<Car> list

and i want to remove an item from this list based on a property of the car

i want something like:

list.RemoveWhere(r=>r.Year > 2000)

does something like this exist ?

i am doing this over and over so i want to avoid copying the list each time to just remove one item

like image 761
leora Avatar asked Jul 24 '10 14:07

leora


2 Answers

Very late to the party but for any one would comes across this problem, here is a cleaner solution:

MyList.RemoveAll( p => p.MyProperty == MyValue );
like image 184
TheSoul Avatar answered Oct 15 '22 11:10

TheSoul


IEnumberable is immutable, but you can do something like this:

list = list.Where(r=>r.Year<=2000)

or write an extension method:

public static IEnumerable<T> RemoveWhere<T>(this IEnumerable<T> query, Predicate<T> predicate)
{ 
    return query.Where(e => !predicate(e));
}
like image 16
sloth Avatar answered Oct 15 '22 11:10

sloth