Meidi
Meidi

Reputation: 572

How do I select a desired row in a grouped result using c# LINQ

I have a Customer table like this

ID EndDate 
1  2/11/2010
1  3/14/2011
2  5/3/2011
2  12/1/2011
3  4/5/2010

I want to take the maximum date's row for each ID group the result like this:

ID EndDate
1  3/14/2011
2  12/1/2011
3  4/5/2010

How do I use one fluent syntax in c# (without looping or 2nd statement) to get the result back?

Customers.GroupBy( c => c.ID ).....//How do I proceed?

Upvotes: 3

Views: 89

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564333

You can use:

var results = Customers.GroupBy(c => c.ID)
                       .Select(
                          g => g.OrderByDescending(c => c.EndDate).First() );

Upvotes: 5

Related Questions