简体   繁体   English

Linq问题的小组和计数

[英]Group and Count in Linq issue

I am working on a C# project using LINQToSQL,But right now I am having a problem with the following query: 我正在使用LINQToSQL开发一个C#项目,但是现在我遇到了以下查询的问题:

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

As you can see I am doing a LEFT OUTER JOIN and grouping by the CustomerID , and everything goes well so far. 正如您所看到的,我正在进行LEFT OUTER JOIN并按CustomerID分组,到目前为止一切顺利。 But when I see the results I realize that the Customers that does not have any Order , has a "1" in their Count field. 但是当我看到结果时,我意识到没有任何OrderCustomers在他们的Count字段中有一个“1”。

Why is that? 这是为什么? The Count field is supposed to have a "0" in these cases, What am I doing wrong? 在这些情况下, Count字段应该为“0”,我做错了什么?

I found this questions here: 我在这里发现了这个问题:

linq-count-query-returns-a-1-instead-of-a-0 LINQ-计数查询返回-A-1-代替-的-A-0

linq-to-sql-joining-query-returning-1-instead-of-0 LINQ到SQL接合用查询返回-1-代替-的-0

but none of them has been helpful to me, I hope someone can help, thank you in advance. 但是没有一个对我有帮助,我希望有人可以提供帮助,提前谢谢你。

There will still be a record, even if it's null - a set that contains "NULL" is still a row - that's why it's saying there is 1 record. 仍然会有一条记录,即使它是空的 - 包含“NULL”的集合仍然是一行 - 这就是为什么它说有1条记录。 If you give the Count method an argument for what records to count, it should work better. 如果给Count方法一个参数来计算要记录的记录,它应该更好。

Count = g.Count(a => a.SomeNullableField != null)

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. join...into执行组连接 ,因此订单在前两行代码中按CustomerId分组。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM