Michel
Michel

Reputation: 23615

Entity framework get latest records in list of records with date

i have a sql server table with records (that isn't new) it has 1 or more records (measurements) for a person, and all records have a datetime field. So for person 1 i have 5 records / measurements, dated jan 1, jan 2, feb 8, march 19 and july 2. i have maybe 10 records for person 2, and the dates are different too.

Now i want to select for both person 1 and person 2 the latest record; for both persons 1 record, with the newewst datetime in the datetime field.

Can that be done with the EF?

Kind regards, Michel

example data

personId Date Length

1 01-13-2009 180

1 01-14-2009 190

1 01-15-2009 184

2 02-18-2009 170

2 01-17-2009 190

In this table, i would like the latest record for person 1 (= row 3) and for person 2 (=row 4)

Upvotes: 3

Views: 5230

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126547

from p in Context.WhateverYourTableNameIs
group p by p.PersonId into g
select new 
{
    PersonId = g.Key
    MostRecentMeasurementDate = (DateTime?)
                                (from m in g
                                 order by m.Date desc
                                 select m.Date).FirstOrDefault())
}

Upvotes: 6

Related Questions