Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Group By and select collection

Tags:

c#

linq

group-by

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.

like image 681
jenson-button-event Avatar asked May 17 '12 14:05

jenson-button-event


People also ask

How can we do a GroupBy using LINQ query?

You can also use Into Group with GroupBy in VB.Net. LINQ query is ended with the help Select or Groupby clause. It can also support method syntax in both C# and VB.Net languages. As shown in example 2.

What is GroupBy in C#?

GroupBy() Method in C# The GroupBy() is an extension method that returns a group of elements from the given collection based on some key value. The following is our array − int[] arr = { 2, 30, 45, 60, 70 }; Now, we will use GroupBy() to group the elements smaller than 50 − arr.

How do you sum two columns in LINQ?

Items select new { Sum(p. Total), Sum(p. Done)};

How do you write a count query in LINQ?

Count() methodIEnumerable<string> strings = new List<string> { "first", "then", "and then", "finally" }; // Will return 4 int result = strings. Count(); NOTE: The Count() LINQ method (an extension method to IEnumerable<T> ) is slightly different from the Count property on List<T> .


1 Answers

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.

like image 52
Ani Avatar answered Oct 11 '22 12:10

Ani