Linq问题中的分组和计数 [英] Group and Count in Linq issue
问题描述
我正在使用LINQToSQL进行C#项目,但是现在我对以下查询有疑问:
I am working on a C# project using LINQToSQL,But right now I am having a problem with the following query:
var groupByQuery = (from c in db.Customers
join o in db.Orders on c.CustomerID equals o.CustomerID into lf1
from or in lf1.DefaultIfEmpty()
group c by c.CustomerID into g
select new
{
CustomerID = g.Key,
Count = g.Count()
}
).OrderBy(x => x.Count);
如您所见,我正在执行LEFT OUTER JOIN
并按CustomerID
分组,到目前为止一切正常.但是,当我看到结果时,我意识到没有任何Order
的Customers
在其Count
字段中具有"1".
As you can see I am doing a LEFT OUTER JOIN
and grouping by the CustomerID
, and everything goes well so far. But when I see the results I realize that the Customers
that does not have any Order
, has a "1" in their Count
field.
那是为什么?在这种情况下,Count
字段应该为"0",我在做什么错了?
Why is that? The Count
field is supposed to have a "0" in these cases, What am I doing wrong?
我在这里发现了以下问题:
I found this questions here:
linq-count-query-returns-a -1-而不是a-0
linq-to-sql-joining-query -returning-1-inst-of-0
但是他们都没有对我有帮助,我希望有人能帮助您,谢谢您.
but none of them has been helpful to me, I hope someone can help, thank you in advance.
推荐答案
您使事情变得太复杂了. join...into
执行组联接,因此订单按<在您的前两行代码中.这应该起作用:
You're making things too complicated. join...into
performs a group join, so the Orders are grouped by CustomerId
within your first two lines of code. This should work:
var groupByQuery = (from c in db.Customers
join o in db.Orders on c.CustomerID equals o.CustomerID into lf1
select new
{
CustomerID = c.Id,
Count = lf1.Count()
}
).OrderBy(x => x.Count);
这篇关于Linq问题中的分组和计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!