尝试通过记录类型(即行的第一个字符)来计算文件中特定行的出现次数。我的总行数是正确的,我的“其他”计数是正确的,但我的切换结果并没有计算总行数。foreach 运行了 13 次,但计数没有更新。
static void Main(string[] args)
{
int i1LineCount = 0;
int i2LineCount = 0;
int i3LineCount = 0;
int i4LineCount = 0;
int iOther = 0;
int iCount = File.ReadLines(@"c:\single.txt").Count();
foreach (string line in File.ReadLines(@"c:\single.txt"))
{
String sFirstChar = line.Substring(0, 1);
switch (sFirstChar)
{
case "1":
i1LineCount = i1LineCount+1;
break;
case "2":
i2LineCount = i2LineCount+1;
break;
case "3":
i3LineCount = i3LineCount+1;
break;
case "4":
i4LineCount = i4LineCount+1;
break;
default:
iOther = iOther+1;
break;
}
}
Console.WriteLine("Line Count = " + iCount);
Console.WriteLine("1 lines = " + i1LineCount);
Console.WriteLine("2 lines = " + i1LineCount);
Console.WriteLine("3 lines = " + i1LineCount);
Console.WriteLine("4 lines = " + i1LineCount);
Console.WriteLine("Other lines = " + iOther);
}
我正在阅读的 txt 文件看起来像(没有 # 前面的 ',没有它我无法让它显示出来):
'# \ 1 4 4 2 2 2 3 2 4 4 '#
我得到的结果是:
Line Count = 13
1 lines = 1
2 lines = 1
3 lines = 1
4 lines = 1
Other lines = 3
我应该得到:
Line Count = 13
1 lines = 1
2 lines = 4
3 lines = 1
4 lines = 4
Other lines = 3