简体   繁体   English

linq从对象数组中删除item,其中property等于value

[英]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.

相关问题 从对象列表中删除属性“ colName”的值与给定数组“ AllCols”中的任何项匹配的所有对象 - From a list of objects remove all objects where value of a property “colName” matches Any item in a given array “AllCols” Linq查询从列表中获取总和,其中某些属性等于 - Linq query get sum from list where certain property equals to C# - 检查列表是否包含属性等于值的对象? - C# - check if list contains an object where a property equals value? Linq获取自定义对象的列表,其中字典属性中包含的某个值等于一个特定值 - Linq to get list of custom objects where a certain value contained within dictionary property equals a specific value 创建LINQ表达式,其中参数等于object - Creating a LINQ Expression where parameter equals object Linq where element.equals一个数组 - Linq where element.equals one array 使用包含到 EF for SQL IN() 的表达式获取 LINQ,其中实体上的子属性等于值 - Expression to get LINQ with Contains to EF for SQL IN() where on entities child's property equals value 是否有Linq操作从项目列表中检索特定项目,其中该项目具有应为唯一的属性的属性值? - Is there a Linq operation to retrieve specific items from a list of items where the item has a property value for a property which should be unique? Linq其中值在Array中 - Linq Where value is in Array Linq 选择实体属性值与另一个列表中任何项目的属性值匹配的位置 - Linq select where entity property value matches value of property of any item in another List
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM