4
How do I get the penultimate record from an Entity Framework table
4
How do I get the penultimate record from an Entity Framework table
4
You can do it like this:
var penultimoRegistro = db.Entidade.OrderByDescending(/*ordenação*/).Take(2).Last();
What this code does is take the last two records according to the specified ordering and save in the variable the last record of these two (since the ordering 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 as per your order, and skips a record of the Single()
serves to make the return be one T
instead of IEnumerable<T>
.
In the end, the end result is the same.
Browser other questions tagged c# asp.net-mvc .net entity-framework
You are not signed in. Login or sign up in order to post.
You can use Skip so you don’t have to return 2 and select the last one. Just switch
Take(2).Last();
forSkip(1).Take(1).Single();
– Bruno Piovan
That too, I will add this option.
– Jéf Bueno