简体   繁体   中英

Using LINQ to get objects of type from a list

Please see the code below:

public interface IVehicle {
}

public class Car : IVehicle {
}

public class Lorry : IVehicle {
}

and the client code below:

var Vehicles = new List<IVehicle>();
Vehicles.Add(new Car());
Vehicles.Add(new Lorry());
var Vehicles2 = new List<IVehicle>();
Vehicles2.Add(Vehicles.OfType<Car>() as IVehicle);

A null value is added to the list after the last line is run. How can I ensure that the Car is added to the list.

I got my idea from here: LINQ selection by type of an object .

There can be a lot of Car items within your List<IVehicle> so you have to use AddRange

Vehicles2.AddRange(Vehicles.OfType<Car>());

approach with Linq Where

Vehicles2.AddRange(Vehicles.Where(x =>  x.GetType() == typeof(Car)));

@fubo, it is guaranteed that there will only every be one

If there is always one and you just want to add that one with Add you can also use Single() to select that Car - note: Single() throws an Exception if there isn't exactly one item.

Vehicles2.Add(Vehicles.OfType<Car>().Single());

I would note that the actual problem is that you're casting IEnumerable<Car> to IVehicle . The cast apparently fails and as operator returns null .

So the solution here, as others have already pointed, is to either obtain a single IVehicle object (eg via .Single or .First ), or to add the whole sequence to the list via .AddRange .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM