Search code examples
c#.netlinqsql-order-byprojection

order by and project distinct objects


I have data something like this:

 Id  |  Customer  |  CartTotal
-------------------------------
 1   |      a     |     100 
 2   |      a     |     50
 3   |      b     |     110
 4   |      b     |     128

I need to order it by CartTotal (descending) and return distinct customers so that I should have this in my result set:

 Id  |  Customer  |  CartTotal
-------------------------------
  4  |      b     |     128
  1  |      a     |     100

I believe I need to do an order and projection. I'm working with a strongly typed IList<> datasource. I'm new to LINQ.. any help would be greatly appreciated.


Solution

  • Something like the following should do what you're after:

    var filteredPurchases = purchases.OrderByDescending(p => p.CartTotal)
        .GroupBy(p => p.Customer)
        .Select(g => g.First());
    

    It will return the purchase with the maximum CartTotal for each Customer, giving the desired result.