Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting last two rows in a text file

Tags:

c#

asp.net

linq

So I am creating a list of lines in a text file like this:

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

and looping through the 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>");
}

Similary like I access the first two rows I would like to access the last and second last row individually

like image 624
StevieB Avatar asked Dec 20 '11 22:12

StevieB


1 Answers

Here you can take advantage of LINQ once 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 retrieve them individually:

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 item, which we then grab with First(). This can probably be optimized.

Again, you might want to familiarize yourself with LINQ since it's a real time-saver sometimes.

like image 172
Dennis Traub Avatar answered Nov 15 '22 07:11

Dennis Traub