FiveTools
FiveTools

Reputation: 6040

Linq groupby query with projection

I'm trying to group orders by customer id then project the orders returned (by customer) into a List. Trying to figure out how I would do this?

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

Upvotes: 4

Views: 2410

Answers (3)

sharp_net
sharp_net

Reputation: 737

I would do something like below. I like to select columns that are needed instead of getting all.

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

}

Upvotes: 1

neontapir
neontapir

Reputation: 4736

Reed's right, though I believe you could also use the result selector to achieve this, like so:

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

(I don't have a compiler in front of me to verify.)

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564931

The result is an IGrouping<TKey, T>, which is itself an IEnumerable<T>, so you can do:

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

(Note that this assumes Orders is assignable from a List<Order>.)

Upvotes: 4

Related Questions