如何将带有group by子句的SQL select Count转换为LINQ?

时间:2013-01-01 09:39:02

标签: c# .net sql linq linq-to-sql

如何将以下SQL查询转换为LINQ?

SELECT [EmpUserName],[LeaveTypeName],Count([NoOfDays]) as 'Count'
FROM [NSL.LeaveSystem02].[dbo].[ProcessedCPLeaves]
GROUP BY [LeaveTypeName],[EmpUserName],[ProcessingDate]

请帮助。

由于

2 个答案:

答案 0 :(得分:2)

尝试一下,

from a in ProcessedCPLeaves
group a by new 
    {
        LeaveTypeName = a.LeaveTypeName,
        EmpUserName = a.EmpUserName,
        ProcessingDate = a.ProcessingDate
    } into g
select new
    {
        EmpUserName = g.Key.EmpUserName
        LeaveTypeName = g.Key.LeaveTypeName
        TotalCount = g.Count()
    }

答案 1 :(得分:2)

以下是方法语法

 ProcessedCPLeaves
.GroupBy(item => new { 
                 LeaveTypeName = item.LeaveTypeName,
                 EmpUserName = item.EmpUserName,
                 ProcessingDate = item.ProcessingDate
}).Select (grouping => new {
                 EmpUserName =grouping.Key.EmpUserName,
                 LeaveTypeName = grouping.Key.LeaveTypeName,
                 TotalCount= grouping.Count()
});