如何在LINQ查询中强制转换? [英] How do I cast in a LINQ query?
问题描述
有没有办法使用显式强制转换操作符作为LINQ查询的一部分?
我试图显示我想用代码做什么下面。这是一个有点人为的例子,因为在实际的应用程序中,Car可能是Vehicle的子类,但请假装由于某种原因,父子类关系不合适。此外,为了简单起见,假设我知道所有的车辆都是汽车。
public class 车辆
{
}
公开 类 Car
{
public static 显式 operator Car(Vehicle v)
{
}
}
public CarCache
{
公众 IList< car> SomeCars
{
get
{
// 我可以在这里使用单个LINQ查询将车辆作为汽车返回吗?
}
}
私人 IEnumerable< vehicle> _车辆;
}
我很难写上面评论中指出的代码。任何人都可以帮助我(如果确实可以的话)?
我对LINQ很新,所以如果这个问题的答案非常明显,我会道歉。
我尝试过的事情:
我试过平常的谷歌搜索但是我找不到的例子似乎与我想做的事情完全相关。
public IList< Car> SomeCars
{
get
{
return _vehicles .Select(v = > (Car)v)。ToList();
}
}
试试这个:
列表与LT;汽车和GT; cars = carCache.Where(x => x Car).ToList< Car>();
>
就我个人而言,我的做法略有不同:
public class Vehicle
{
}
public 类汽车:车辆
{这意味着每辆车也是车辆,因此您可以将所有车辆类型存储在缓存中:
public class CarCache
{
public IList< Car> SomeCars
{
get
{
return _vehicles .Where(v = > v Car).Cast< Car>()。ToList() ;
}
}
私人列表< Vehicle> _vehicles = new 列表< Vehicle>();
public void 添加(车辆v){_ vehicles.Add(v); }
}
(不要将集合存储为IEnumerable:它没有Add方法,因此很难更改内容!)
Is there a way to use an explicit cast operator as a part of a LINQ query?
I have tried to show what I want to do with the code below. It is a somewhat contrived example because in a real application a Car would probably be a subclass of a Vehicle, but please pretend that for some reason a parent-subclass relationship is not appropriate. Also, for the sake of simplicity, assume I know all the vehicles are cars.
public class Vehicle
{
}
public class Car
{
public static explicit operator Car( Vehicle v )
{
}
}
public CarCache
{
public IList<car> SomeCars
{
get
{
// Can I use a single LINQ query here to return the vehicles as cars?
}
}
private IEnumerable<vehicle> _vehicles;
}
I'm struggling to write the code indicated by the comment above. Can anyone help me out (if it is indeed possible)?
I'm fairly new to LINQ, so I apologise if the answer to this question is blindingly obvious.
What I have tried:
I have tried the usual Googling but no example I have been able to find seems to relate exactly to what I want to do.
public IList<Car> SomeCars { get { return _vehicles.Select(v => (Car)v).ToList(); } }
Try this:
List<Car> cars = carCache.Where(x=>x is Car).ToList<Car>();
Personally, I'd do it slightly differently:
public class Vehicle { } public class Car : Vehicle {What that means is that every Car is also a Vehicle, so you can store all Vehicle types in your cache:
public class CarCache { public IList<Car> SomeCars { get { return _vehicles.Where(v => v is Car).Cast<Car>().ToList(); } } private List<Vehicle> _vehicles = new List<Vehicle>(); public void Add(Vehicle v) { _vehicles.Add(v); } }
(Don't store the collection as an IEnumerable: it doesn't have an Add method so it's difficult to change the content!)
这篇关于如何在LINQ查询中强制转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!