LINQ多个与Group By连接

时间:2014-12-23 11:42:38

标签: c# asp.net linq

在尝试了很多之后我决定在这里发一个问题。我的代码如下:

var query =
            //Customers
            from customer in context.Customers

            //Engineer 1
            join engineer1 in context.Employees on customer.PrimaryEngineer equals
            engineer1.EmployeeId into eng1 
            from engineer1 in eng1.DefaultIfEmpty()

            //Engineer Top
            join engineerTop in context.Employees on customer.TopEngineer equals 
            topEngineer.EmployeeId into top
            from engineerTop in top.DefaultIfEmpty()

然后,我希望我按照三个表中的属性进行分组:客户,员工(每个工程师重复一次)

如何按三个表中的属性进行分组?

下一个代码:

            group new {customer, engineer1, engineerTop} by new {customer.Name .....}
由于engineer1和engineerTop来自同一个环境,

不起作用?

我对此非常困惑。

感谢大家的帮助

1 个答案:

答案 0 :(得分:1)

由于具有相同名称的多个属性,您可能需要为分组中的匿名类型属性指定名称。 (EmployeeId的两倍?)

    var query = (
        //Customers
        from customer in context.Customers

        //Engineer 1
        join engineer1 in context.Employees on customer.PrimaryEngineer equals
        engineer1.EmployeeId into eng1 
        from engineer1 in eng1.DefaultIfEmpty()

        //Engineer Top
        join engineerTop in context.Employees on customer.TopEngineer equals 
        engineerTop.EmployeeId into top
        from engineerTop in top.DefaultIfEmpty()
        group new {customer, engineer1, engineerTop} by new {CustName = customer.Name, EmpId1 = engineer1.EmployeeId, EmpId2 = engineerTop.EmployeeId} into grp
        select new
        {
            Name = grp.Key.CustName,
            EmpId1 = grp.Key.EmpId1,
            EmpId2 = grp.Key.EmpId2
        });