Linq .GroupBy()有计数

时间:2016-07-28 02:02:44

标签: c# asp.net-mvc linq

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

                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

我试图总结一下,在没有循环的情况下传回我的viewmodel。这是我试图实现的结果。

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来达到我想要的效果?这是最好的方法吗?

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分: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;
}

答案 2 :(得分: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