简体   繁体   English

使用LINQ从列表中获取类型的对象

[英]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. 如何确保将Car添加到列表中。

I got my idea from here: LINQ selection by type of an object . 我从这里得到了一个主意: 按对象类型选择LINQ

There can be a lot of Car items within your List<IVehicle> so you have to use AddRange 您的List<IVehicle>可能有很多Car项目,因此您必须使用AddRange

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

approach with Linq Where LINQ的办法Where

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

@fubo, it is guaranteed that there will only every be one @fubo,可以保证只有一个

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. 如果总有一个,而您只想用“ Add将其Add ,则还可以使用Single()选择该Car注意:如果没有正好一个项目, Single()会引发异常。

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

I would note that the actual problem is that you're casting IEnumerable<Car> to IVehicle . 我会注意到实际的问题是您将IEnumerable<Car>强制转换为IVehicle The cast apparently fails and as operator returns null . 强制转换显然失败, as操作符返回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 . 所以这里的解决方案,因为其他人已经指出的,是要么获得单一IVehicle对象(例如通过.Single.First ),或整个序列添加到通过列表.AddRange

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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