2016-07-28 77 views
1

我有一个表,我需要在报告中总结。这是我的示例表。
Linq .GroupBy()与计数

   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来实现我想要的结果?这是最好的方法吗?

+0

包括当前查询你正在使用 –

+1

同意@不幸运..和你正在工作的数据库 –

+2

请澄清项目列表是固定为3还是你想要的列数根据不同的项目而有所不同 –

回答

6

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() 
       }; 
+0

不错的解决方案。我将.First()更改为.FirstOrDefault()。 – pacopicorico

3

如果项目是固定的:

public List<OrderViewModel> GetCustOrders() 
{ 
    var query = orders 
     .GroupBy(c => c.CustomerName) 
     .Select(o => new OrderViewModel{ 
      CustomerName = o.Key, 
      Shoe = o.Where(c => c.OrderType == "Shoe").Count(c => c.CustomerId), 
      Hat = o.Where(c => c.OrderType == "Hat").Count(c => c.CustomerId), 
      Sock = o.Where(c => c.OrderType == "Sock").Count(c => c.CustomerId), 
      Total = o.Count(c => c.CustomerId) 
     }); 

    return query; 
} 
0

使用SQL是一种选择,我测试了它,并得到你想要什么:

select p.*, t.total as 'Total Orders' from 
(
    select CustomerName, count(CustomerId) total from Orders group by CustomerName 
) as t inner join 
(
    select * from Orders 
    pivot(count(CustomerId) 
     for OrderType in ([Shoe], [Hat], [Sock]) 
     ) as piv 
)as p on p.CustomerName = t.CustomerName