4

我正在尝试按客户 ID 对订单进行分组,然后将返回的订单(按客户)投影到列表中。试图弄清楚我将如何做到这一点?

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

3 回答 3

4

result一个IGrouping<TKey, T>,它本身就是一个IEnumerable<T>,所以你可以这样做:

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

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

于 2012-08-20T21:18:51.363 回答
2

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

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)
{

}
于 2012-08-20T22:43:26.423 回答
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();

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

于 2012-08-20T21:23:04.673 回答