Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq To Entities Get 2nd Last entry In List

I have the following code which returns a list of Objects.

var listOfLogins = _logService.GetLogEventsByItemID(137).ToList();

I would like to get the 2nd last object in this list.

Does anyone know how to do this using Linq to Entities?

Thanks.

like image 449
tcode Avatar asked Jan 16 '23 00:01

tcode


1 Answers

var secondlast = _logService.GetLogEventsByItemID(137)
    .Reverse()
    .Skip(1)
    .Take(1)
    .FirstOrDefault();

Update
@Dherik makes a good point in his comment that .Reverse is not actually supported in LINQ to Entities and will result in the query being evaluated at the point of calling reverse, rather than at the point of calling .FirstOrDefault. See here for all (not) supported methods.

The alternative (LINQ to Entities friendly) solution requires that you have a suitable field to order by (which must be the case anyway otherwise "second last" has no relevance):

var secondlast = _logService.GetLogEventsByItemID(137)
    .OrderByDescending(e => e.EventDate /* could be any db field */)
    .Skip(1)
    .Take(1)
    .FirstOrDefault();
like image 78
Paul Fleming Avatar answered Jan 24 '23 20:01

Paul Fleming