[英]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: IEnumberable
是不可变的,但你可以这样做:
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? 如果您正在使用
IEnumerable<T>
,那么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: 如果您正在使用
ICollection<T>
并且您不仅仅获得过滤结果但真正打算操纵源集合,您可以为集合创建自己的定制扩展:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.