gpt4 book ai didi

c# - LINQ - 左连接、分组依据和计数

转载 作者:IT王子 更新时间:2023-10-29 03:30:45 27 4
gpt4 key购买 nike

假设我有这个 SQL:

SELECT p.ParentId, COUNT(c.ChildId)
FROM ParentTable p
LEFT OUTER JOIN ChildTable c ON p.ParentId = c.ChildParentId
GROUP BY p.ParentId

如何将其转换为 LINQ to SQL?我卡在了 COUNT(c.ChildId),生成的 SQL 似乎总是输出 COUNT(*)。这是我到目前为止得到的:

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into j1
from j2 in j1.DefaultIfEmpty()
group j2 by p.ParentId into grouped
select new { ParentId = grouped.Key, Count = grouped.Count() }

谢谢!

最佳答案

from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into j1
from j2 in j1.DefaultIfEmpty()
group j2 by p.ParentId into grouped
select new { ParentId = grouped.Key, Count = grouped.Count(t=>t.ChildId != null) }

关于c# - LINQ - 左连接、分组依据和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/695506/

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