How to group a complex list of objects using LINQ?
        Posted  
        
            by Daoming Yang
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Daoming Yang
        
        
        
        Published on 2010-04-10T21:12:09Z
        Indexed on 
            2010/04/10
            21:33 UTC
        
        
        Read the original article
        Hit count: 592
        
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()
                   });
© Stack Overflow or respective owner