0

I'm very new to LINQ, I've searched the boards but none of the other q/a's give a complete sample. I need to query with LINQ a strongly typed IList<> object and I must:

  1. Sum by a property
  2. Group by a property
  3. Order by the same property I did Sum on
  4. Limit the result to top 2

For example if my data is like this:

 Id  |  Customer  |  CartTotal
-------------------------------
 1   |      a     |     100 
 2   |      a     |     50
 3   |      b     |     110
 4   |      b     |     128
 5   |      c     |     75
 6   |      c     |     30

My result needs to be like this where I've limited it top 2, grouped by customer, and done a sum on CartTotal:

Customer  |  CartTotal
----------------------
    b     |     238 
    a     |     150

What's the best way of accomplishing this?

ekad
  • 14,436
  • 26
  • 44
  • 46
SR8
  • 53
  • 5

2 Answers2

1

It's all a matter of chaining together the right extension methods. We want to first group by customer - GroupBy - then for each group project to the customer and the cart total - Select, order by the cart total descending - OrderByDescending and finally take the top 2 - Take :

var results = customerOrders.GroupBy(c=> c.Customer)
                            .Select(g=> new 
                             { 
                               Customer = g.Key, 
                               CartTotal = g.Sum(x=>x.CartTotal) 
                             })
                            .OrderByDescending(x=> x.CartTotal)
                            .Take(2);
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
1
var query = carts.GroupBy(c => c.Customer)
                 .Select(g => new { Customer = g.Key, Total = g.Sum(p => p.CartTotal)})
                 .OrderByDescending(c => c.Total)
                 .Take(2);
Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116