1

I have a list of objects that have a following structure

public class Order
{
    public Guid OrderId { get;set;}
    public DateTime OrderDate {get;set;}
    public Guid CustomerId { get;set;}
}

From the list I have to chose for each customer newest order. I know I need to use group by CustomerId, but how do I select only newest order from the group? Thanks

cAMPy
  • 567
  • 2
  • 8
  • 25
  • Please show what you have tried – Gilad Green Aug 24 '17 at 07:12
  • orders.GroupBy(x => x.CustomerId) that gives me a set, now I need to order the orders inside the groups by the orderdate and pick only the newest one from each group. I don't know how to achieve that. – cAMPy Aug 24 '17 at 07:15

1 Answers1

3

You probably looking for something like that

orders.GroupBy(o => o.CustomerId).Select(g => g.OrderByDescending(o => o.OrderDate).First());

So within each group you will sort by the order date and then select the first one.

DerApe
  • 3,097
  • 2
  • 35
  • 55