Daoming Yang
Daoming Yang

Reputation: 1325

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.

Upvotes: 4

Views: 5047

Answers (2)

Mark Byers
Mark Byers

Reputation: 837946

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.

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532445

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()
                       });

Upvotes: 3

Related Questions