pbz*_*pbz 165 .net c# linq linq-to-sql
假设我有这个SQL:
SELECT p.ParentId, COUNT(c.ChildId)
FROM ParentTable p
LEFT OUTER JOIN ChildTable c ON p.ParentId = c.ChildParentId
GROUP BY p.ParentId
Run Code Online (Sandbox Code Playgroud)
如何将其转换为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() }
Run Code Online (Sandbox Code Playgroud)
谢谢!
Meh*_*ari 186
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) }
Run Code Online (Sandbox Code Playgroud)
Amy*_*y B 55
考虑使用子查询:
from p in context.ParentTable
let cCount =
(
from c in context.ChildTable
where p.ParentId == c.ChildParentId
select c
).Count()
select new { ParentId = p.Key, Count = cCount } ;
Run Code Online (Sandbox Code Playgroud)
如果查询类型通过关联连接,则简化为:
from p in context.ParentTable
let cCount = p.Children.Count()
select new { ParentId = p.Key, Count = cCount } ;
Run Code Online (Sandbox Code Playgroud)
Ere*_*mez 34
最后答复:
你不应该需要的左连接在所有如果你正在做的是伯爵().请注意,join...into实际上它被转换为GroupJoin返回分组,new{parent,IEnumerable<child>}因此您只需要调用Count()该组:
from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into g
select new { ParentId = p.Id, Count = g.Count() }
Run Code Online (Sandbox Code Playgroud)
在扩展方法语法join into等效于GroupJoin(而join没有一个into是Join):
context.ParentTable
.GroupJoin(
inner: context.ChildTable
outerKeySelector: parent => parent.ParentId,
innerKeySelector: child => child.ParentId,
resultSelector: (parent, children) => new { parent.Id, Count = children.Count() }
);
Run Code Online (Sandbox Code Playgroud)
小智 7
(from p in context.ParentTable
join c in context.ChildTable
on p.ParentId equals c.ChildParentId into j1
from j2 in j1.DefaultIfEmpty()
select new {
ParentId = p.ParentId,
ChildId = j2==null? 0 : 1
})
.GroupBy(o=>o.ParentId)
.Select(o=>new { ParentId = o.key, Count = o.Sum(p=>p.ChildId) })
Run Code Online (Sandbox Code Playgroud)
虽然LINQ语法背后的想法是模拟SQL语法,但您不应该总是考虑直接将SQL代码转换为LINQ.在这种特殊情况下,我们不需要进行分组,因为join into是一个组连接本身.
这是我的解决方案:
from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into joined
select new { ParentId = p.ParentId, Count = joined.Count() }
Run Code Online (Sandbox Code Playgroud)
与此处的大多数投票解决方案不同,我们在Count中不需要j1,j2和null检查(t => t.ChildId!= null)