【发布时间】: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))
{
?
}
【问题讨论】:
使用 linq 我想检查某个条件,如果满足该条件,我想从列表中删除该对象
伪代码
if any object inside cars list has Manufacturer.CarFormat != null
delete that object
if (muObj.Cars.Any(x => x.Manufacturer.CarFormat != null))
{
?
}
【问题讨论】:
使用List函数RemoveAll,可以
muObj.Cars.RemoveAll(x => x.Manufacturer.CarFormat != null);
【讨论】:
List 上的普通方法。
我在
IList上没有这个RemoveAll方法
这是因为RemoveAll 是List<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);
}
【讨论】: