How do I get the penultimate record of a table with Entity Framework
How do I get the penultimate record of a table with Entity Framework
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.