如何在linq中的多个表上应用group By

时间:2012-12-19 07:24:21

标签: linq c#-4.0 linq-to-sql linq-to-entities

我在linq中有这样的查询

   var result = from item1 in context.ServicePriceInsertData
                                 join item2 in context.GroupMasterInsert
                                 on item1.G_Id equals item2.Group_Id
                                 join item3 in context.EmployeeServices
                                 on item1.Service_Id equals item3.E_ServiceId

                                 into dept
                                 from item4 in dept.DefaultIfEmpty()

                                 select new 
                                 {

                                     Service_Name = item1.S_Description,
                                     Group_Name = item2.Group_Name,
                                     ServiceId = item4.E_Id == null ? 1 : item4.E_Id

                                 };

现在我需要按Service和Group_Name计算ServiceId。 请帮帮我?

1 个答案:

答案 0 :(得分:0)

这是未经测试但请尝试..我希望它可以帮助您并了解如何分组和计数linq。有关详细信息linq + C# + group by + count

        var result = from item1 in context.ServicePriceInsertData
                     join item2 in context.GroupMasterInsert on item1.G_Id equals item2.Group_Id
                     join item3 in context.EmployeeServices on item1.Service_Id equals item3.E_ServiceId
                     group new {  item1.S_Description, item2.Group_Name, item1 } by new { item.S_Description } into g

                     select new
                     {

                         Service_Name = g.Key.S_Description,
                         Group_Name = g.Key.Group_Name,
                         Counted =  (int?)g.Count()
                     };