Linq to SQL - Group By and Count

本文关键字:By and Count Group to SQL Linq | 更新日期: 2023-09-27 18:23:56

我正在尝试转换这个查询(已经工作)

SELECT Building.NAME, COUNT([User].ID)
FROM BuildingUser
INNER JOIN Building ON Building.ID = BuildingUser.ID_BUILDING
INNER JOIN [User] ON [User].ID = BuildingUser.ID_USER
GROUP BY Building.NAME

从Linq到SQL,但我不知道自己做错了什么。看看我的

from buildinguser in db.GetTable<BuildingUser>()
join building in db.GetTable<Building>()
on buildinguser.ID_BUILDING equals building.ID
join user in db.GetTable<User>()
on buildinguser.ID_USER equals user.ID
group building by building.NAME into grpBuilding
select new
{
    building = grpBuilding.Key,
    users = 
};

我只需要对我的建筑进行分组,并计算每个建筑有多少用户。

Linq to SQL - Group By and Count

只需使用Count方法:

from buildinguser in db.GetTable<BuildingUser>()
join building in db.GetTable<Building>()
on buildinguser.ID_BUILDING equals building.ID
join user in db.GetTable<User>()
on buildinguser.ID_USER equals user.ID
group building by building.NAME into grpBuilding
select new
{
    building = grpBuilding.Key,
    users = grpBuilding.Count()
};