linq to sql中的Group by子句问题

时间:2015-02-15 08:43:25

标签: linq

我想在linqsql中进行此查询。 请帮忙。我是linq的新用户,对group by clause感到有疑问。

以下是sql query

select count(USERID), d.DEPTNAME from USERS u
join department d on u.DEPTID = d.DEPTID
group by u.DEPTID, d.DEPTNAME

1 个答案:

答案 0 :(得分:1)

更直接的翻译是这样的:

var query =
    from u in db.Users
    join d in db.Departments on u.DeptId equals d.DeptId
    group d by new { d.DeptId, d.DeptName } into g
    select new
    {
        g.Key.DeptName,
        Count = g.Count(),
    };

虽然我认为最好这样写:

// looks like we're counting users in each department
var query =
    from d in db.Departments
    select new
    {
        d.DeptName,
        Count = db.Users.Count(u => u.DeptId == d.DeptId),
    };