通过LINQ删除父类类型列表的项目

时间:2014-01-27 09:18:03

标签: c# linq list generics

我有一个父类列表,包含由子类组成的对象项。例如

Class Vehicle
{
String Name;
}

Class Car: Vehicle
{
int Speed;
}

Class Bike: Vehicle
{
int Milage;
}

List<Vehicle> transports = new List<Vehicle>;
transports.Add(new Car{Name = "Fiat", Speed = 70});
transports.Add(new Bike{Name = "Bajaj", Milage = 70});
transports.Add(new Car{Name = "BMW", Speed = 100});

现在我要删除速度为100的汽车类型的物品。我该怎么做。优先通过linq

3 个答案:

答案 0 :(得分:5)

transports.RemoveAll(x => x is Car && (x as Car).Speed == 100);

答案 1 :(得分:3)

这就是你想要的:

var carsToRemove = transports.OfType<Car>().Where(c => c.Speed == 100).ToArray();

foreach (var car in carsToRemove)
{
    transports.Remove(car);
}

答案 2 :(得分:1)

试试此代码: 您可以使用RemoveAll

删除项目
transports.RemoveAll(c => c is Car && (c as Car).Speed == 100);

我希望它会对你有所帮助。