我想创建一个类似于SqlDataReader.Read()的功能
我正在从..txt/..csv读取一个平面文件,并将其作为datatable返回到处理业务逻辑的类中。这将遍历datatable的行,并将数据转换为结构化数据库。我将此结构用于多个导入源。
但是,大文件的工作非常非常慢。我花了2小时的时间来处理30 MB的数据,我想把它降到30分钟。这个方向上的一个步骤是,不要将整个文件读取到DataTable中,而是逐行处理它,并防止内存被记录。
像这样的东西是理想的: PSEUDOCODE。
FlatFileReader ffr = new FlatFileReader(); //Set FlatFileParameters
while(ffr.ReadRow(out DataTable parsedFlatFileRow))
{
//...Business Logic for handling the parsedFlatFileRow
}如何实现像.ReadRow(out DataTable parsedFlatFileRow) 这样的方法?
这个方向对吗?
foreach(obj in ff.lazyreading()){
//Business Logic
}
...
class FlatFileWrapper{
public IEnumerable<obj> lazyreading(){
while(FileReader.ReadLine()){
yield return parsedFileLine;
}
}
}发布于 2013-10-30 10:37:36
正如提姆已经提到的,File.ReadLines是您所需要的:
“使用ReadLines时,可以在返回整个集合之前开始枚举字符串集合”
您可以创建一个使用该方法的解析器,如下所示:
// object you want to create from the file lines.
public class Foo
{
// add properties here....
}
// Parser only responsibility is create the objects.
public class FooParser
{
public IEnumerable<Foo> ParseFile(string filename)
{
if(!File.Exists(filename))
throw new FileNotFoundException("Could not find file to parse", filename);
foreach(string line in File.ReadLines(filename))
{
Foo foo = CreateFoo(line);
yield return foo;
}
}
private Foo CreateFoo(string line)
{
// parse line/create instance of Foo here
return new Foo {
// ......
};
}
}使用代码:
var parser = new FooParser();
foreach (Foo foo in parser.ParseFile(filename))
{
//...Business Logic for handling the parsedFlatFileRow
}发布于 2013-10-30 09:43:45
可以使用File.ReadLines,它的工作方式类似于StreamReader
foreach(string line in File.ReadLines(path))
{
//...Business Logic for handling the parsedFlatFileRow
}https://stackoverflow.com/questions/19678686
复制相似问题