我有一个父类列表,包含由子类组成的对象项。例如
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
答案 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);
我希望它会对你有所帮助。