如何在两个列表之间返回多个连接

时间:2014-09-30 16:05:33

标签: c# linq

我有2个清单。一个叫做Records1,另一个叫Records2。 Records1有3个带有徽章编号的字段,而Records2有1个带有徽章编号的字段。

我想将Records2徽章字段与Records1中的每个其他徽章字段相匹配,并在下面的查询中返回3个名称。 我认为查询是正确的,但我在匿名类型语句中得到了2个错误。

我该如何解决?

var query1 = from i in Records1
         join e in Records2 on i.Responsi equals e.Badge
         join e1 in Records2 on i.Author equals e1.Badge
         join e2 in Records2 on i.ByN equals e2.Badge

         select new
         {
             i.Author,
             i.CompletionDate,
             i.CompletedBy,
             i.Responsi,
             i.Auth,
             i.ByN,
             i.IsClose,
             e.EmployeeName,
             e.Discipline,
             e1.EmployeeName, // error: anonymous type cannot have multiple properties with the same name
             e2.EmployeeName, // error: anonymous type cannot have multiple properties with the same name
             e.DeptSub
            };

3 个答案:

答案 0 :(得分:2)

您可以通过以下方式解决此问题

select new
{
    Author = i.Author,
    // Set names for the other properties     
    Name1 = e1.EmployeeName, 
    Name2 = e2.EmployeeName, 
    DeptSub = e.DeptSub
};

在你的评论中,你不能使用匿名类型属性的名称。因此,这些名称将由您选择的变量名称自动推断。因此,选择e.EmployeeName将被分配给名为EmployeeName的变量。当e1.EmployeeName被分配时,将出现命名混淆。因此,上述方法是克服这个问题的一个技巧。

答案 1 :(得分:1)

正如您的错误所暗示的那样,您的匿名对象不能具有两个相同名称的属性,您可以这样做:

var query1 = from i in Records1
     join e in Records2 on i.Responsi equals e.Badge
     join e1 in Records2 on i.Author equals e1.Badge
     join e2 in Records2 on i.ByN equals e2.Badge

     select new
     {
         Author = i.Author,
         CompletionDate = i.CompletionDate,
         CompletedBy = i.CompletedBy,
         Responsi = i.Responsi,
         Auth = i.Auth,
         ByN = i.ByN,
         IsClose = i.IsClose,
         EmployeeName = e.EmployeeName,
         Discipline = e.Discipline,
         EmployeeName2 = e1.EmployeeName, // error: anonymous type cannot have multiple properties with the same name
         EmployeeName3 = e2.EmployeeName, // error: anonymous type cannot have multiple properties with the same name
         DeptSub = e.DeptSub
        };

您的匿名类型将成为一个类似于您无法预期以下内容的对象:

// No worky
public class Foo
{
    public string Bar;
    public string Bar; // can't have two properties of same name in class
}

虽然这有效:

public class Foo
{
    public string Bar;
    public string Bar2;
}

答案 2 :(得分:0)

匿名对象必须具有不同的名称。所以给他们起名字。

 var query1 = from i in Records1
     join e in Records2 on i.Responsi equals e.Badge
     join e1 in Records2 on i.Author equals e1.Badge
     join e2 in Records2 on i.ByN equals e2.Badge

     select new
     {
         i.Author,
         i.CompletionDate,
         i.CompletedBy,
         i.Responsi,
         i.Auth,
         i.ByN,
         i.IsClose,
         e.EmployeeName,
         e.Discipline,
         name1 = e1.EmployeeName, 
         name2 = e2.EmployeeName, 
         e.DeptSub
        };

这将确保创建的匿名对象没有两个具有相同名称的属性