How to group a complex list of objects using LINQ?
- by Daoming Yang
I want to select and group the products, and rank them by the number of times they occur.
For example, 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.
A friend helped me with the following code. It could be compiled, but it did not return any value/result. I used the watch window for the query and it gave me "The name 'query' does not exist in the current context".
Can anyone help me?
Many thanks.
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()
});