How to use Linq to select and group a complex child from a parent list

How to use Linq to select and group a complex child from a list of parents.

I have an OrderList , each of the order objects has an OrderProductVariantList (OrderLineList), and each of the OrderProductVariant has a ProductVariant, and then ProductVariant will have a Product object containing product information.

My goal is to select and group the most popular products from the list of orders.

Can anyone help me with this?

Many thanks.

+4
source share
2 answers

It's hard to understand your description, but I think you just want to exit the Products and rank them by the number of times. SelectMany will be useful for this.

var query = orderList.SelectMany( o => o.OrderLineList ) // results in IEnumerable<OrderProductVariant> .Select( opv => opv.ProductVariant ) .Select( pv => p.Product ) .GroupBy( p => p ) .Select( g => new { Product = g.Key, Count = g.Count() }); 
+3
source

The query is not a result. To view the result, you can iterate over the query object:

 foreach (var result in query) { Console.WriteLine(result); } 

As to why the request was not available in the viewport, I can only assume that it was either not yet in scope or already out of scope. Try to set a breakpoint on the line immediately after the line that you placed, where you assign the request.

+1
source

Source: https://habr.com/ru/post/1306560/


All Articles