我正在使用File.ReadLines方法加载一个文件(文件可能会变得非常大,所以我使用了这个而不是ReadAllLines)
我需要访问每一行并对其执行操作。 所以我的代码是这样的
IEnumerable<String> lines = File.ReadLines("c:myfile.txt", new UTF8Encoding());
StringBuilder sb = new StringBuilder();
int totalLines = lines.Count(); //used for progress calculation
//use for instead of foreach here - easier to know the line I'm on for progress percent complete calculation
for(int i = 0; i < totalLines; i++){
//for example get the line and do something
sb.Append(lines.ElementAt(i) + "rn");
//get the line again using ElementAt(i) and do something else
//...ElementAt(I)...
}
所以我的瓶颈是每次访问ElementAt(i)
,因为它必须遍历整个 IEmumerable 才能到达位置 i。
有没有办法继续使用File.ReadLines,但以某种方式改进它?
编辑 - 我在开始时计数的原因是我可以计算进度完成以显示给用户。 这就是为什么我删除了foreach以支持for。
使用foreach
怎么样? 它旨在处理这种情况。
IEnumerable<String> lines = File.ReadLines("c:myfile.txt", new UTF8Encoding());
StringBuilder sb = new StringBuilder();
string previousLine = null;
int lineCounter = 0;
int totalLines = lines.Count();
foreach (string line in lines) {
// show progress
float done = ++lineCounter/totalLines;
Debug.WriteLine($"{done*100:0.00}% complete");
//get the line and do something
sb.AppendLine(line);
//do something else, like look at the previous line to compare
if (line == previousLine) {
Debug.WriteLine($"Line {lineCounter} is the same as the previous line.");
}
previousLine = line;
}
当然,您可以使用foreach
而不是for
循环,因此您不必返回并通过其索引引用该行:
foreach (string line in lines)
{
sb.AppendLine(line);
}
您也将不再需要int totalLines = lines.Count();
行,因为您不需要任何内容的计数(除非您使用未显示的位置)。