我收到了一些文件,但我不知道这些文件中有多少列和行。 如何使用通用模型创建通用加载器,我可以随时加载文件但获取不同的内容?
我写了这个,但知道我知道它并不总是同桌......
public override List<Object> getFile(string ab) {
if (ab == "A") {
ab = A;
} else {
ab = B;
}
List<FundPriceModel> models = new List<FundPriceModel>();
FileStream filestream = new FileStream(ab, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(filestream, Encoding.UTF8)) {
string line;
bool isHeader = true;
while ((line = reader.ReadLine()) != null) {
FundPriceModel model = new FundPriceModel();
if (isHeader) {
headers = line.Split(spliter[0]);
isHeader = false;
continue;
}
string[] attributes = line.Split(spliter);
model.LipperID = IfEmptyInt(attributes[0]);
model.PriceDate = IfEmptyDateTime(attributes[1]);
model.PriceCode = safeValue(attributes[2], v => v[0]);
model.PriceType = safeValue(attributes[3], v => v[0]);
model.PriceCurrency = safeValue(attributes[4], v => attributes[4]);
model.PriceValueLC = IfEmptyFloat(attributes[5]);
model.Estimate = safeValue(attributes[6], v => v[0]);
Console.WriteLine(model.LipperID + "\t" + model.PriceDate + "\t" + model.PriceCode + "\t" + model.PriceType +
"\t" + model.PriceCurrency + "\t" + model.PriceValueLC + "\t" + model.Estimate);
models.Add(model);
}
}
}
答案 0 :(得分:0)
如果DataTable足够通用,你可以使用它,它不是真正的模型&#39;。此代码不值得生产,仅演示如何从CSV加载。
private static void Main(string[] args)
{
string filePath = @"C:\temp\tesst.csv";
FileStream filestream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
DataTable inputTable = new DataTable();
using (StreamReader reader = new StreamReader(filestream, Encoding.UTF8))
{
//Get headers and add columns
string headers = reader.ReadLine();
foreach (var s in headers.Split(','))
{
inputTable.Columns.Add(s, typeof (string));
}
//Add rows
string line;
while ((line = reader.ReadLine()) != null)
{
int colIndex = 0;
DataRow dr = inputTable.NewRow();
foreach (var s in line.Split(','))
{
dr[colIndex] = s;
colIndex++;
}
inputTable.Rows.Add(dr);
}
}
}