[英]Group and Count in Linq issue
我正在使用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);
正如您所看到的,我正在进行LEFT OUTER JOIN
并按CustomerID
分组,到目前为止一切顺利。 但是当我看到结果时,我意识到没有任何Order
的Customers
在他们的Count
字段中有一个“1”。
这是为什么? 在这些情况下, Count
字段应该为“0”,我做错了什么?
我在这里发现了这个问题:
但是没有一个对我有帮助,我希望有人可以提供帮助,提前谢谢你。
仍然会有一条记录,即使它是空的 - 包含“NULL”的集合仍然是一行 - 这就是为什么它说有1条记录。 如果给Count
方法一个参数来计算要记录的记录,它应该更好。
Count = g.Count(a => a.SomeNullableField != null)
你的事情太复杂了。 join...into
执行组连接 ,因此订单在前两行代码中按CustomerId
分组。 这应该工作:
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.