Reputation: 6040
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
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
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
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