Linq groupby用投影查询

时间:2012-08-20 21:17:01

标签: linq grouping

我正在尝试按客户ID对订单进行分组,然后将订单(由客户)返回到列表中。试图弄清楚我会怎么做?

 List<OrderGroup> set = OrderRepository.GetAllOrders
     .GroupBy(x => x.CustomerId).Select(result => new OrderGroup
         {
             Orders = ???? //should be all orders from one customer.
         }).ToList();

3 个答案:

答案 0 :(得分:4)

resultIGrouping<TKey, T>,本身就是IEnumerable<T>,所以你可以这样做:

List<OrderGroup> set = OrderRepository.GetAllOrders
                      .GroupBy(x => x.CustomerId)
                      .Select(result => new OrderGroup
                      {
                          Orders = result.ToList()
                      }).ToList();

(请注意,这假定Orders可以从List<Order>分配。)

答案 1 :(得分:1)

我会做类似下面的事情。我喜欢选择所需的列而不是全部。

var customerData = (from cd in OrderRepository.GetAllOrders
                     group cd by new { cd.CustomerId, cd.date } into grp
                    select new
                       {
                           customer_name = grp.FirstOrDefault().custname,
                           total_orders = grp.Count(),  
                           amount = grp.Sum(x => x.total_amt_paid)

                       }).ToList();                    


foreach (var data in customerData)
{

}

答案 2 :(得分:0)

Reed是对的,不过我相信你也可以使用结果选择器实现这一点,如下所示:

List<OrderGroup> set = OrderRepository.GetAllOrders
                         .GroupBy(x => x.CustomerId, // key selector
                           x => x, // element selector
                           result => new OrderGroup
                           {
                              Orders = result.ToList()
                           }) // result selector
                         .ToList();

(我面前没有编译器可以验证。)