StevieB
StevieB

Reputation: 6541

Getting last two rows in a text file

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

Upvotes: 6

Views: 918

Answers (2)

Dennis Traub
Dennis Traub

Reputation: 51654

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.

Upvotes: 11

Steve Wellens
Steve Wellens

Reputation: 20640

This one of the problems of using var when it's not appropriate.

ReadAllLines returns an array of strings: string[]

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

Upvotes: 0

Related Questions