开发者

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 doc开发者_开发问答uments 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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜