简体   繁体   中英

How to use Linq to select and group complex child object from a parents 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()
                       });

A 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 query wasn't available in the watch window, I can only imagine that it either wasn't in scope yet, or it had already gone out of scope. Try putting a breakpoint on the line immediately after the line you posted where you assign to query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM