IEnumberable<Car> list
,我想基于汽车的属性,从这个列表中删除的项
我想是这样的:
list.RemoveWhere(r=>r.Year > 2000)
做这样的事情存在吗?
我这样做一遍又一遍,所以我想避免每次复制列表中只删除一个项目
IEnumberable<Car> list
,我想基于汽车的属性,从这个列表中删除的项
我想是这样的:
list.RemoveWhere(r=>r.Year > 2000)
做这样的事情存在吗?
我这样做一遍又一遍,所以我想避免每次复制列表中只删除一个项目
IEnumberable
是一成不变的,但你可以以这样的事:
list = list.Where(r=>r.Year<=2000)
或写一个扩展方法:
public static IEnumerable<T> RemoveWhere<T>(this IEnumerable<T> query, Predicate<T> predicate)
{
return query.Where(e => !predicate(e));
}
如果您正在使用IEnumerable<T>
工作,怎么样在哪里?
list = list.Where(car => car.Year <= 2000);
如果您正在使用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;
}
}
看到更新的问题 – leora 2010-07-24 14:22:56
看到我更新的答案;-) – 2010-07-24 14:34:24
非常迟到了,但对于任何一个会遇到这个问题,这里是一个清晰的解决方案:
MyList.RemoveAll(p => p.MyProperty == MyValue);
它是一个'清单'或只是一个IEnumerable的''? –
2010-07-24 14:26:42