如果有一个csv文件,其数据会不时增加。现在我需要做的是阅读最后 30,000 行。
Code :
string[] lines = File.ReadAllLines(Filename).Where(r => r.ToString() != "").ToArray();
int count = lines.Count();
int loopCount = count > 30000 ? count - 30000 : 0;
for (int i = loopCount; i < lines.Count(); i++)
{
string[] columns = lines[i].Split(',');
orderList.Add(columns[2]);
}
它工作正常,但问题是
File.ReadAllLines(Filename)
读取完整的文件会导致性能下降。我想要类似的东西,它只读取最后 30,000 行,并迭代整个文件。
PS:我正在使用.Net 3.5。 .Net 3.5 中不存在 Files.ReadLines()
您可以使用File.ReadLines()
方法而不是使用File.ReadAllLines()
来自 MSDN:文件.ReadLines() http://msdn.microsoft.com/en-us/library/dd383503%28v=vs.110%29.aspx
The 读行 and 读取所有行方法的区别如下:
当你使用ReadLines时,你可以在之前开始枚举字符串集合
返回整个集合;当你使用ReadAllLines时,你必须
等待整个字符串数组返回,然后才能访问
数组。
因此,当你在处理非常大的文件,
读行可以更有效率。
解决方案1 :
string[] lines = File.ReadAllLines(FileName).Where(r => r.ToString() != "").ToArray();
int count = lines.Count();
List<String> orderList = new List<String>();
int loopCount = count > 30000 ? 30000 : 0;
for (int i = count-1; i > loopCount; i--)
{
string[] columns = lines[i].Split(',');
orderList.Add(columns[2]);
}
解决方案2:如果您正在使用 .NET Framework 3.5,正如您在下面的评论中所说,您不能使用File.ReadLines()
方法,因为它是可用的.NET 4.0
.
您可以按如下方式使用 StreamReader:
List<string> lines = new List<string>();
List<String> orderList = new List<String>();
String line;
int count=0;
using (StreamReader reader = new StreamReader("c:\\Bethlehem-Deployment.txt"))
{
while ((line = reader.ReadLine()) != null)
{
lines.Add(line);
count++;
}
}
int loopCount = (count > 30000) ? 30000 : 0;
for (int i = count-1; i > loopCount; i--)
{
string[] columns = lines[i].Split(',');
orderList.Add(columns[0]);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)