简体   繁体   English

如何使用LINQ / Lambda将结果选择到在对象内声明的对象中?

[英]How to select results into an object declared within an object using LINQ/Lambda?

I've got a result set returned from a stored procedure and I need to populate the fields of an object from those results. 我有一个从存储过程返回的结果集,我需要从这些结果中填充对象的字段。 The trouble is my object declares another object that has fields that need populating from the results. 麻烦的是我的对象声明了另一个对象,该对象具有需要从结果中填充的字段。

I've got a Vehicle object and declared within my Vehicle object I've got a Truck object. 我有一个Vehicle对象,并在我的Vehicle对象中声明了我有Truck对象。 I can't access the fields of the Truck object with dot notation. 我无法使用点表示法访问Truck对象的字段。 Simplified code and classes. 简化的代码和类。

return dc.GetVehicleList(localDateTimeOffset).Select(p => new Vehicle
{
     VehicleNumber = p.VehicleNumber
     Truck.TruckNumber = p.TruckNumber /* This does not work */
}).Cast<IVehicle>().ToList();

public class Vehicle
{
   public int VehicleNumber;
   public Truck Truck;
}

public class Truck
{
   public TruckNumber;
}

Using LINQ/Lambda how do I gain access to the members of my Truck object declared within the Vehicle object so I can set those values from the result set? 使用LINQ / Lambda,如何访问在Vehicle对象中声明的Truck对象的成员,以便可以从结果集中设置这些值?

You need to create the inner object along with the outer one: 您需要创建内部对象以及外部对象:

return dc.GetVehicleList(localDateTimeOffset).Select(p => new Vehicle
{
     VehicleNumber = p.VehicleNumber
     Truck = new Truck 
     {
        TruckNumber = p.TruckNumber
     }
}).Cast<IVehicle>().ToList();

You can also create the truck object in the constructor of the Vehicle class and keep your query. 您还可以在Vehicle类的构造函数中创建truck对象,并保留查询。

public class Vehicle
{
   public Vehicle()
   {
      Truck = new Truck();
   }

   public int VehicleNumber;
   public Truck Truck;
}

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

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