C#链接如何使用两个相关列表中的子列表填充父列表

时间:2018-03-08 06:50:57

标签: c# linq dapper nested-lists

我是Linq的新手,但需要快速完成一些代码。我有两个班:

public class SAPMember
{
    public string EmployeeNumber { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<CostCentre> CostCentres { get; set; }
}

 public class CostCentre
{
    public string EmployeeNumber { get; set; }
    public string CostCentreCode { get; set; }
    public string Division { get; set; }
}

每个SAP会员都可以拥有一个或多个CostCentres。

这是我最初填充两个独立列表的代码(使用Dapper),然后我希望将其合并到一个带有子列表的列表中:

    _SAPMembers = new List<SAPMember>();

   string sql = @"SELECT EmployeeNo as EmployeeNumber,
              LastName, FirstName
              FROM Employees";

   _SAPMembers = DbConn.Query<SAPMember>(sql).ToList();

   List<CostCentre> _CostCentres = new List<CostCentre>();

   string sql2 = @"SELECT EmployeeNo as EmployeeNumber, CostCentreCode,
                DivisionDescription as Division
                FROM Employees";

  _CostCentres = DbConn.Query<CostCentre>(sql2).ToList();

我已尝试过Linq分组和加入等,但无法正确使用语法,而且我的_SAPMembers列表中填入了员工详细信息以及相关的costcentres列表。

代码示例将不胜感激。我已经看到这可能来自一个更复杂的Dapper查询,但我认为对于我的技能水平linq可能是一个更好的解决方案。

1 个答案:

答案 0 :(得分:1)

正如阿米特所说,我可以使用Dapper,因为:(注意:我将CostCentre键更改为EmpNo)

 if (_SAPMembers == null)

{         列出_SAPMembers = new List();

var lookup = new Dictionary<string, SAPMember>();

var result = DbConn.Query<SAPMember, CostCentre, SAPMember>(@"
select DISTINCT e.EmployeeNo as EmployeeNumber, e.LastName, e.FirstName, c.EmployeeNo as EmpNo
, c.CostCentreCode as Name, c.DivisionDescription as Division
FROM EmployeeListing e
join EmployeeListing c on e.EmployeeNo = c.EmployeeNo
where e.TerminationDate is null and c.TerminationDate is null", (e, c) =>
{
    if (!lookup.TryGetValue(e.EmployeeNumber, out SAPMember sapMember))
        lookup.Add(e.EmployeeNumber, sapMember = e);

    if (sapMember.CostCentres == null)
        sapMember.CostCentres = new List<CostCentre>();

    sapMember.CostCentres.Add(c);

    return sapMember;
}, splitOn: "EmpNo");

_SAPMembers = result.Distinct().ToList();

}     return _SAPMembers;