【问题标题】:Linq query result into two objectsLinq 查询结果分为两个对象
【发布时间】:2012-05-23 19:19:58
【问题描述】:

我目前有以下 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 对象的实例?

谢谢, 理查德

【问题讨论】:

  • 我太傻了,我需要做的就是: List list = query.Select(a => new DriverODSJoined() { driver = new Driver() { address1 = a.driver .address1 }, check = new BLL.DVLA.Licence() { id = a.licence.id } } ).ToList();
  • 您应该发表您的评论作为答案并接受它。这将帮助其他有类似问题的人
  • 我试过了,但我必须等待 7 个小时才能发布,所以必须回来。至少想发表评论,这样没有人会浪费时间来回答它!

标签: .net linq linq-to-sql


【解决方案1】:

我很快就想通了,当然我必须先实例化包含对象中的每个对象,然后再将值分配给它们的成员变量。所以这里是例子:

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();

【讨论】:

  • 作为更新,我发现当左连接的许可证为空时,我必须这样做:check = a.licence = null ? new BLL.DVLA.Licence() : new BLL.DVLA.Licence() { id = a.licence.id },因为进程作为许可证对象上的成员变量(如 id)是非可为空的整数
猜你喜欢
  • 2020-03-26
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多