简体   繁体   中英

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:

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. But when I see the results I realize that the Customers that does not have any Order , has a "1" in their Count field.

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-instead-of-a-0

linq-to-sql-joining-query-returning-1-instead-of-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. If you give the Count method an argument for what records to count, it should work better.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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