Mark Mark -4 years ago 86
C# Question

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. I can't access the fields of the Truck object with dot notation. 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?

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download