Linq To Entities Get Second Last Entry In List

I have the following code that returns a list of objects.

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

I would like to get the second last object on this list.

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

Thanks.

+4
source share
2 answers
 var secondlast = _logService.GetLogEventsByItemID(137) .Reverse() .Skip(1) .Take(1) .FirstOrDefault(); 

Refresh
@Dherik makes a comment in his comment that .Reverse is not actually supported in LINQ to Entities and will cause the request to be evaluated at the reverse call point, not at the .FirstOrDefault call .FirstOrDefault . See here for all supported methods (not).

An alternative solution (LINQ to Entities friendly) requires that you have a suitable field for ordering (this should be anyway, otherwise the "second last" does not matter):

 var secondlast = _logService.GetLogEventsByItemID(137) .OrderByDescending(e => e.EventDate /* could be any db field */) .Skip(1) .Take(1) .FirstOrDefault(); 
+9
source
  int[] items = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int item = items.Skip(items.Count() - 2).Take(1).Single(); //will return 9 

like this?

0
source

All Articles