简体   繁体   English

如何在Linq中使用分组和计数

[英]How to use group by and having count in Linq

I am having trouble trying to convert the following query from SQL to Linq, in particular with the having count and group by parts of the query: 我在尝试将以下查询从SQL转换为Linq时遇到了麻烦,尤其是在查询中有count和group by的情况下:

select ProjectID
from ProjectAssociation

where TeamID in ( select TeamID 
                  from [User]
                  where UserID in (4))
group by ProjectID
having COUNT(TeamID) = (select distinct COUNT(TeamID)
                        from [User]
                        where UserID in (4))

Any advice on how to do so would be much appreciated. 任何有关如何这样做的建议将不胜感激。

var groups = from pa in ProjectAssociation let teamIds = User.Where(u => u.UserID == 4).Select(u => u.TeamID) where teamIds.Contains(pa.TeamID) group pa by pa.ProjectID; var groups =来自ProjectAssociation中的pa,让teamIds = User.Where(u => u.UserID == 4)。选择(u => u.TeamID),其中teamIds.Contains(pa.TeamID)由pa.ProjectID分组

var result = from g in groups
   let count = User.Where(u => u.UserID == 4).Select(u => u.TeamID).Distinct().Count()
   where g.Count() == count
   select g.Key;

Or maybe more optimal: 也许更理想:

var teamIds = User.Where(u => u.UserID == 4).Select(u => u.TeamID).AsEnumerable();
var groups = ProjectAssociation.Where(pa => teamIds.Contains(pa.TeamID)
   .GroupBy(pa => pa.ProjectID);
var result = from g in groups
       let count = teamIds.Distinct().Count()
       where g.Count() == count
       select g.Key;

By the way, i think that by 顺便说一句,我认为

select distinct COUNT(TeamID)

you meant: 你的意思是:

select COUNT(distinct TeamID)

There is a tool (cheap) that will convert queries like this for you. 有一个工具(廉价)可以为您转换这样的查询。 It's called Linqer. 叫林克 I own a copy and have found that it's able to convert event the most complex of queries. 我拥有一个副本,并且发现它能够将事件转换为最复杂的查询。 The URL is http://www.sqltolinq.com/ 该URL是http://www.sqltolinq.com/

It's not free, but it's pretty inexpensive and has a 30 day trial. 它不是免费的,但价格却很便宜,并且有30天的试用期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM