Catch Penultimate record of a table with Entity Framework

Asked

Viewed 1,358 times

4

How do I get the penultimate record from an Entity Framework table

1 answer

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.

See an example on dotNetFiddle

  • You can use Skip so you don’t have to return 2 and select the last one. Just switch Take(2).Last(); for Skip(1).Take(1).Single();

  • That too, I will add this option.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.