Get Penultimate record of a table with Entity Framework

4

How do I get the penultimate record of a table with Entity Framework

    
asked by anonymous 30.11.2015 / 17:37

1 answer

3

You can do this:

var penultimoRegistro = db.Entidade.OrderByDescending(/*ordenação*/).Take(2).Last();

What this code does is to get the last two records according to the specified ordering and save the last record of those two in the variable (since the sort is Descending ).

Edit:

You can also do

db.Entidade.OrderByDescending(/*ordenação*/).Take(2).Skip(1).Take(1).Single();

This code takes the last two records according to their ordering, and skips a record the Single() is to make the return be T instead of IEnumerable<T> .

At the end, the end result is the same.

See an example in dotNetFiddle

    
30.11.2015 / 17:42