简体   繁体   中英

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

聚会很晚,但任何人都会遇到这个问题,这是一个更清洁的解决方案:

MyList.RemoveAll( p => p.MyProperty == MyValue );

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));
}

If you are working with IEnumerable<T> , how about Where?

list = list.Where(car => car.Year <= 2000);

If you are working with ICollection<T> and you not just get a filtered result but really intend to manipulate the source collection, you can create an own tailor made extension for collection:

  public static class CollectionExtensions {
     public static ICollection<T> RemoveWhere<T>(this ICollection<T> collection, Func<T, bool> predicate) {
        List<T> toRemove = collection.Where(item => predicate(item)).ToList();
        toRemove.ForEach(item => collection.Remove(item));
        return collection;
     }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM