Linq to SQL - Group By和Count

时间:2013-07-20 01:28:59

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

我正在尝试转换此查询(已在运行)

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 to 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 = 
};

我只需要对我的建筑物进行分组,并计算每个建筑物的用户数量。

1 个答案:

答案 0 :(得分:9)

只需使用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()
};