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.
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.
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.
Items select new { Sum(p. Total), Sum(p. Done)};
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> .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With