Here you can use LINQ again:
var numberOfLinesToTake = 2; var lastTwoLines = lines .Skip(Math.Max(0, lines.Count() - numberOfLinesToTake)) .Take(numberOfLinesToTake); var secondToLastLine = lastTwoLines.First(); var lastLine = lastTwoLines.Last();
Or, if you want to get them separately:
var lastLine = lines.Last(); var secondToLastLine = lines.Skip(Math.Max(0, lines.Count() - 2)).Take(1).First();
I added .First() to the end because .Take(1) will return an array containing one element, which we then take First() . Perhaps this will be optimized.
Again, you might want to check out LINQ, as it may be from time to time.
source share