Getting the last two lines in a text file

So, I create a list of lines in a text file as follows:

var lines = File.ReadAllLines("C:\\FileToSearch.txt") .Where(x => !x.EndsWith("999999999999")); 

and scrolling lines like this

 foreach (var line in lines) { if (lineCounter == 1) { outputResults.Add(oData.ToCanadianFormatFileHeader()); } else if (lineCounter == 2) { outputResults.Add(oData.ToCanadianFormatBatchHeader()); } else { oData.FromUsLineFormat(line); outputResults.Add(oData.ToCanadianLineFormat()); } lineCounter = lineCounter + 1; textBuilder += (line + "<br>"); } 

Similarly, as I access the first two lines, I would like to access the last and second last lines separately

+6
source share
2 answers

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.

+11
source

This is one of the problems of using var if it does not fit.

ReadAllLines returns an array of strings: string []

You can get the length of the array and index back from the end.

0
source

Source: https://habr.com/ru/post/904197/


All Articles