Ross Cooper
Ross Cooper

Reputation: 245

Remove item of List of parent class type through LINQ

I have a List of Parent Class, containing items of objects made up of child class. For example

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});

Now I want to delete the items of type car which have speed of 100. How can I do this. Preferable through linq

Upvotes: 0

Views: 622

Answers (3)

Govinda Rajbhar
Govinda Rajbhar

Reputation: 3034

Try this code : you can remove item using RemoveAll

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

i hope it will help you.

Upvotes: 1

svinja
svinja

Reputation: 5576

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

Upvotes: 5

Dennis
Dennis

Reputation: 37770

Is this what you want:

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

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

?

Upvotes: 3

Related Questions