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


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

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

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

Can anyone help me with this?

Many thanks.

Your description is hard to follow, but I think you just want to get out the Products and rank them by the number of times they occur. SelectMany will be helpful 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()