super9
super9

Reputation: 30111

Counts and Loops in C#

This seems like a really simple thing to do but I cant't seem to get my ahead around it. I have 10 documents entitled 1.txt to 10.txt. I just want to count the number of lines in each doc and end up with the final summation of the line counts.

This is where I got to.

    for (int i = 1; i < 11; i++)
    {
        int lineCount = File.ReadLines(@i + ".txt").Count();
        lineCount += lineCount; 
        Console.WriteLine("Total IDs: " + lineCount);
    }

UPDATE My docs have carriage returns at the bottom of them which I do not want to include in the count.

Upvotes: 1

Views: 7558

Answers (3)

Ed Swangren
Ed Swangren

Reputation: 124642

You have declared lineCount inside of the loop, so it is destroyed and created again after each iteration, i.e., you are only seeing the last result. Declare lineCount outside the scope of the loop instead.

Upvotes: 3

user541686
user541686

Reputation: 210445

lineCount += lineCount; is the same as lineCount *= 2;; is that what you intended?

Upvotes: 2

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56390

You are reinitializing lineCount every time. Change it like so:

int lineCount = 0;
for (int i = 1; i < 11; i++)
{
    lineCount += File.ReadLines(@i + ".txt").Count();
}
Console.WriteLine("Total IDs: " + lineCount);

This way you don't reinitialize lineCount every time, and you are simply adding the Count to it for each iteration.

Upvotes: 9

Related Questions