为了简化这篇文章,假设我在Orders表中有如下数据。这里CustomerId是Customers表的外键。 问题:我们如何编写LINQ查询来查找每个客户订购的蔬菜(V)和水果(F)的数量?
订单表:
undefined
我可以按如下方式计算每个客户的订单数量。 OrderId | CustomerId | OrderType
1 | 11 | V
2 | 11 | V
3 | 11 | F
4 | 11 | V
5 | 12 | V
6 | 15 | F
7 | 15 | V
8 | 15 | F
:
But how about number of Vegetables and number of Fruits in each order?
答案 0 :(得分:2)
您可以使用子查询:
var Query1 = from o in Orders
group o by o.CustomerId into grp
select new {
CustomerId = grp.Key,
OrderCount = grp.Count(),
OrderCounts = from g in grp
group g by g.OrderType into grp2
select new { OrderType = grp2.Key, Count = grp2.Count() }
};
或者您可以按CustomerId
和OrderType
进行分组:
var Query1 = from o in Orders
group o by new { o.CustomerId, o.OrderType } into grp
select new {
CustomerId = grp.Key.CustomerId,
OrderType = grp.Key.OrderType,
OrderCount = grp.Count()
};
他们都将返回相同的数据,但形式略有不同。