对于空组,LINQ计数返回1而不是零

Gre*_*reg 0 c# linq entity-framework group-by

我有这个SQL查询:

SELECT oy.ownerId, oy.Year,  COUNT(doc.Id) as docCount FROM aavabruf.owneryears oy 
left join vastdocuments doc
on oy.ownerId = doc.Ownerid and  oy.Year =  doc.Year
group by oy.ownerid, oy.year
order by docCount
Run Code Online (Sandbox Code Playgroud)

它将docCount显示为在vastdocuments表中没有文档匹配的OwnerId,Year对的ZERO.

我尝试使用建议的左外连接解决方​​案对LINQ做同样的事情:

from oy in OwnerYears
join doc in VaStDocuments on new {oy.OwnerId, oy.Year} equals new {doc.OwnerId , doc.Year} into docS
from docIfNull in docS.DefaultIfEmpty()
group oy by new {oy.OwnerId, oy.Year} into g
orderby g.Count() ascending
select new { OwnerId = g.Key.OwnerId,  Year = g.Key.Year, docCount = g.Count()}
Run Code Online (Sandbox Code Playgroud)

但是,对于不存在于VastDocuments表中的OwnerId,Year组,我将docCount设置为ONE,而不是ZERO.如果我删除了

来自docS.DefaultIfEmpty()中的docIfNull

行"空"组将不会显示.

我怎样才能将Count视为零,就像在SQL查询中一样?我尝试了以下方法:

Count = docIfNull == null?0:g.Count()

但是在这种情况下我收到一个错误:

当前上下文中不存在名称"docIfNull"

Jon*_*eet 5

最简单的方法是计算非空值:

g.Count(x => x != null)
Run Code Online (Sandbox Code Playgroud)

我建议在之后移动订单,select这样你就可以避免重复自己:

select new { g.Key.OwnerId, g.Key.Year, DocCount = g.Count(x => x != null) } into result
orderby result.DocCount
select result
Run Code Online (Sandbox Code Playgroud)

但是,我注意到目前你还没有使用 docIfNull ...所以我怀疑你的加入并没有真正做你想要的.也许你应该使用

group docIfNull by new { oy.OwnerId, oy.Year } into g
Run Code Online (Sandbox Code Playgroud)