LINQ - 左加入,集团通过和Count [英] LINQ - Left Join, Group By, and Count

查看:193
本文介绍了LINQ - 左加入,集团通过和Count的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有这个SQL语句:

  SELECT p.ParentId,COUNT(c.ChildId)
从ParentTable p
  LEFT OUTER JOIN ChildTable C对p.ParentId = c.ChildParentId
GROUP BY p.ParentId
 

我怎样才能把它理解的LINQ to SQL?我被困在COUNT(c.ChildId),生成的SQL似乎总是输出COUNT(*)。以下是我有这么远:

 由对在context.ParentTable
加入c。在context.ChildTable上p.ParentId等于c.ChildParentId到J1
从J2在j1.DefaultIfEmpty()
一群J2通过p.ParentId到分组
选择新{的ParentId = grouped.Key,计数= grouped.Count()}
 

感谢您!

解决方案

 由对在context.ParentTable
加入c。在context.ChildTable上p.ParentId等于c.ChildParentId到J1
从J2在j1.DefaultIfEmpty()
一群J2通过p.ParentId到分组
选择新{的ParentId = grouped.Key,计数= grouped.Count(T =>!t.ChildId = NULL)}
 

Let's say I have this SQL:

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

How can I translate this into LINQ to SQL? I got stuck at the COUNT(c.ChildId), the generated SQL always seems to output COUNT(*). Here's what I got so far:

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

Thank you!

解决方案

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

这篇关于LINQ - 左加入,集团通过和Count的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆