LINQ To SQL - get the latest records matching where clauses

Given something like the following (just arranged as an example)

Employee ID | Time in | Position | Shift length  
1 | April 1 08:00 | Manager | 8  
0 | April 1 08:00 | Maint | 8  
1 | April 2 08:00 | Manager | 8  
2 | April 1 08:00 | Clerk | 4  
1 | April 3 08:00 | Manager | 8  
0 | April 2 12:00 | Maint | 1  
0 | April 3 12:00 | Maint | 4  

If you are given a specific date, I need to get the most recent entry for each employee ID that occurred before that date (based only on Time In)

So, if the given date was, for example

April 3, 5:00

I expect the following lines to appear

Employee ID | Time in | Position | Shift length  
1 | April 2 08:00 | Manager | 8  
2 | April 1 08:00 | Clerk | 4  
0           | April 2 14:00 | Maint    | 1  

.

, , . , .

.

+3
1

, - :

var query = from row in context.Whatever
            where row.TimeIn < specifiedDate
            group row by row.EmployeeID into g
            select g.OrderByDescending(r => r.TimeIn).First();

, :

  • , .
  • ( )

( g.OrderBy(r => r.TimeIn).Last() - , , SQL.)

+7

Source: https://habr.com/ru/post/1756028/


All Articles