jenson-button-event jenson-button-event - 3 months ago 35
C# Question

LINQ Group By and select collection

I have this structure

Customer
- has many Orders
- has many OrderItems


I want to generate a list of
CustomerItems
via LINQ given a subset of
OrderItems
:

List of new { Customer, List<OrderItem> Items }


which is a grouping of all the items a Customer has ordered from the subset of items

How can i use LINQ to back track through the order and group by Customer to generate this object?

so far I'm on something like

items
.GroupBy(i => i, i => i.Order.Customer, (i, customer) => new {customer, i})


But thats obviously not a List. I'm guessing I need a SelectMany in there somewhere, but could do with some pointers.

Ani Ani
Answer

I think you want:

items.GroupBy(item => item.Order.Customer)
     .Select(group => new { Customer = group.Key, Items = group.ToList() })
     .ToList() 

If you want to continue use the overload of GroupBy you are currently using, you can do:

items.GroupBy(item => item.Order.Customer, 
              (key, group) =>  new { Customer = key, Items = group.ToList() })
     .ToList() 

...but I personally find that less clear.

Comments