如何使用Linq中没有重复项的左连接填充集合对象

时间:2016-09-09 15:19:11

标签: c# linq

如何使用Linq中没有重复项的左连接填充集合对象。

public class List1
{
    public string EmpID { get; set; }
    public string EmpName { get; set; }
}

public class List2
{
    public string EmpID { get; set; }
    public string Addr1 { get; set; }
    public string Addr2 { get; set; }
}

List<List1> list1Obj = new List<List1>();
List<List2> list2Obj = new List<List2>();

list1Obj.Add(new List1 { EmpID = "001", EmpName = "EmpName1" });
list1Obj.Add(new List1 { EmpID = "002", EmpName = "EmpName2" });
list1Obj.Add(new List1 { EmpID = "003", EmpName = "EmpName3" });
list1Obj.Add(new List1 { EmpID = "004", EmpName = "EmpName4" });

list2Obj.Add(new List2 { Addr1 = "Addr11", Addr2 = "Addr21", EmpID = "001" });
list2Obj.Add(new List2 { Addr1 = "Addr12", Addr2 = "Addr22", EmpID = "001" });
list2Obj.Add(new List2 { Addr1 = "Addr13", Addr2 = "Addr23", EmpID = "002" });
list2Obj.Add(new List2 { Addr1 = "Addr14", Addr2 = "Addr24", EmpID = "002" });
list2Obj.Add(new List2 { Addr1 = "Addr15", Addr2 = "Addr25", EmpID = "003" });

如何使用linq左连接填充List<Employee>以下没有重复项?

public class Employee
{
    public string EmpID { get; set; }
    public string EmpName { get; set; }
    public List<Address> EmpAddress { get; set; }
}

我试过下面的代码。它返回带有重复行的结果..

var employeeList =
    (from table1 in list1Obj
    join table2 in list2Obj on table1.EmpID equals table2.EmpID into t
    from st in t.DefaultIfEmpty()
    select new Employee
    {
        EmpID = table1.EmpID,
        EmpName = table1.EmpName,
        EmpAddress = (from s in list2Obj
                     where s.EmpID == table1.EmpID
                     select new Address { Addr1=s.Addr1, Addr2=s.Addr2}).ToList()

    })

2 个答案:

答案 0 :(得分:2)

Join通常会通过匹配内部记录的计数重复外部记录。你真正需要的是GroupJoin

  

群组加入&LT; TOuter,TINNER,TKEY的,TResult&GT;生成分层结果,这意味着来自外部的元素与来自内部的匹配元素的集合配对。 GroupJoin使您可以将结果基于外部的每个元素的整组匹配。

var employeeList =
    (from e in list1Obj
     join a in list2Obj on e.EmpID equals a.EmpID into aGroup
     select new Employee
     {
         EmpID = e.EmpID,
         EmpName = e.EmpName,
         EmpAddress = 
             (from a in aGroup
              select new Address
              {
                  Addr1 = a.Addr1,
                  Addr2 = a.Addr2,
              }).ToList()
     }).ToList();

答案 1 :(得分:0)

使用Lambda表达式可以按照以下方式完成

var employeeList2 = list1Obj.GroupJoin(list2Obj, l1 => l1.EmpID, l2 => l2.EmpID, (l1, l2) => new
        {
            l1,
            l2
        }).Select(row => new Employee
        {

            EmpID = row.l1.EmpID,
            EmpName = row.l1.EmpName,
            EmpAddress = row.l2.Select(add => new Address
            {
                Addr1 = add.Addr1,
                Addr2 = add.Addr2
            }).ToList()

        });