Linq Count and Group by

时间:2015-03-23 16:28:46

标签: c# linq

我有一个SQL查询,我需要转变为Linq但是对于我的生活,我似乎无法对结果进行分组。

这是原始的SQL查询:

select UserLevel, count(UserLevel) as count, StudioId
from UserProfile 
where CompletedSetup = 1 
and userid in (select UserId from webpages_UsersInRoles where RoleId = 4) 
group by StudioId, UserLevel
order by StudioId

它返回的内容类似于

UserLevel     Count     StudioId
1             6         1
2             2         1
3             4         1

1 个答案:

答案 0 :(得分:0)

context.UserProfile
.Where(x=>x.CompletedSetup==1 && context.webpages_UsersInRoles.Any(u=>u.UserId == x.UserId && u.RoleId == 4))
.GroupBy(x=>new {x.UserLevel, x.StudioId)
.Select(x=>new {UserLevel = x.Key.UserLevel, StudioId = x.Key.StudioId, count=x.Count()})