我有一个表,需要在报告中进行总结。这是我的样本表。

                Orders
_____________________________________
CustomerId | CustomerName | OrderType
___________|______________|__________
1          |     Adam     | Shoe
1          |     Adam     | Shoe
1          |     Adam     | Shoe
1          |     Adam     | Hat
1          |     Adam     | Hat
2          |     Bill     | Shoe
2          |     Bill     | Hat
3          |     Carl     | Sock
3          |     Carl     | Hat


我试图总结这一点,以便不循环地传回我的视图模型。这是我试图实现的结果。

CustomerName | Shoe | Hat | Sock | Total Orders
------------ | ---- | --- | ---- | ------------
Adam         |   3  |  2  |  0   |      5
Bill         |   1  |  1  |  0   |      2
Carl         |   0  |  1  |  1   |      2

//var resultList = dbContext.Orders.OrderBy(o => o.CustomerId);


如何使用GroupBy和Count达到期望的结果?那是最好的方法吗?

最佳答案

group clause (C# Reference)

var summary = from order in dbContext.Orders
              group order by order.CustomerId into g
              select new {
                  CustomerName = g.First().CustomerName ,
                  Shoe = g.Count(s => s.OrderType == "Shoe"),
                  Hat = g.Count(s => s.OrderType == "Hat"),
                  Sock = g.Count(s => s.OrderType == "Sock"),
                  TotalOrders = g.Count()
              };

10-01 19:35