[英]Custom functionality similar to SqlDataReader.Read()
我想創建一個功能類似於SqlDataReader.Read()
我正在從.txt / .csv中讀取平面文件,並將其作為數據表返回給我的類處理業務邏輯。 這將遍歷數據表的行,並轉換數據,並將其寫入結構化數據庫。 我將此結構用於多個導入源。
不過,大文件確實非常緩慢地工作。 我需要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;
}
}
}
如Tim所述,您需要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
}
您可以使用類似於StreamReader
File.ReadLines
:
foreach(string line in File.ReadLines(path))
{
//...Business Logic for handling the parsedFlatFileRow
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.