Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL - Group By and Count

I'm trying to convert this query (already working)

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

To Linq to SQL, but I don't know what I'm doing wrong. Look at my trying

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

I just need to group my Buildings and count how many users each one has.

like image 442
Gandarez Avatar asked Jan 12 '23 21:01

Gandarez


1 Answers

Simply use the the Count method:

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()
};
like image 131
p.s.w.g Avatar answered Jan 16 '23 00:01

p.s.w.g