Linq查询结果分为两个对象

时间:2012-05-23 19:19:58

标签: .net linq linq-to-sql

我目前有以下linq运行并获取两个强类型对象(DAL.Driver和DAL.Licence)。但是我想将结果转换为包含BLL.Driver和BLL.Licence对象的单个DriverODSJoined对象。

public class DriverODSJoined
{
    public BLL.Driver driver { get; set; }
    public BLL.Licence licence { get; set; }

    public static void GetData()
    {
        DAL.DriverDataContext dataContext = new DAL.DriverDataContext();

        var query = (from d in dataContext.drivers
                     join c in dataContext.licences on d.licence_id equals c.id into t1
                     from t2 in t1.DefaultIfEmpty()
                     select new { Driver = d, Licence = t2 });
    }
}

对于链接查询到一个类对象,我会这样做:

query.Select(a => new BLL.Driver.Driver()
        {
            id = a.Driver.id
            etc
        }).ToList();

所以要填充一个DriverODSJoined列表,我想我会做这样的事情:

  query.Select(a => new BLL.Driver.DriverODSJoined()
        {
            driver.id = a.Driver.id,
            licence.id = t2.id
        }).ToList();

然而它不起作用。我怎么能这样做最终得到一个List,每个List包含一个BLL.Driver和BLL.Licence对象的实例?

谢谢, 理查德

1 个答案:

答案 0 :(得分:2)

我很快就想到了它,当然我必须在为其成员变量赋值之前实例化包含对象中的每个对象。所以这是一个例子:

List<DriverODSJoined> list = query.Select(a => new DriverODSJoined()
{ 
    driver = new Driver()
    { 
        address1 = a.driver.address1
    },
    check = new BLL.DVLA.Licence()
    {
        id = a.licence.id 
    } 
}).ToList();