【问题标题】:remove object from the list if certain statement is true [duplicate]如果某些陈述为真,则从列表中删除对象[重复]
【发布时间】:2015-12-17 20:43:17
【问题描述】:

使用 linq 我想检查某个条件,如果满足该条件,我想从列表中删除该对象

伪代码

if any object inside cars list has Manufacturer.CarFormat != null
delete that object

if (muObj.Cars.Any(x => x.Manufacturer.CarFormat != null))
{
    ?
}

【问题讨论】:

    标签: c# .net linq


    【解决方案1】:

    使用List函数RemoveAll,可以

    muObj.Cars.RemoveAll(x => x.Manufacturer.CarFormat != null);
    

    【讨论】:

    • 从技术上讲,这不是 Linq - 只是 List 上的普通方法。
    • 是的,你是对的。已编辑。
    【解决方案2】:

    我在IList 上没有这个RemoveAll 方法

    这是因为RemoveAllList<T> 上的方法,而不是IList<T>。如果您不想尝试转换为 List<T>(如果失败了怎么办?),那么一种选择是按索引循环(以相反的顺序进行,以免弄乱索引计数:

    for (int i = muObj.Cars.Count - 1; i >= 0; i--)
    {
        if(muObj.Cars[i].Manufacturer.CarFormat != null)
            muObj.Cars.RemoveAt(i);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-18
      • 2019-07-25
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 2013-05-28
      • 2020-11-21
      相关资源
      最近更新 更多