gpt4 book ai didi

c# - 如何在 Linq 中使用分组依据和计数

转载 作者:太空狗 更新时间:2023-10-29 23:19:10 24 4
gpt4 key购买 nike

我在尝试将以下查询从 SQL 转换为 Linq 时遇到问题,尤其是在查询的部分具有计数和分组的情况下:

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))

如有任何建议,我们将不胜感激。

最佳答案

var groups = 来自 ProjectAssociation 中的 pa 让 teamIds = User.Where(u => u.UserID == 4).Select(u => u.TeamID) 其中 teamIds.Contains(pa.TeamID) 按 pa.ProjectID 对 pa 进行分组;

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;

或者更优化:

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;

顺便说一下,我认为通过

select distinct COUNT(TeamID)

你的意思是:

select COUNT(distinct TeamID)

关于c# - 如何在 Linq 中使用分组依据和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2575589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com