使用LINQ访问csv文件

时间:2012-11-09 03:06:42

标签: c#

我有一个c#实验室问题:

这是我的代码todo从csv文件添加数据,编译后它给出了一个错误,当前内容中不存在名称“rows”

foreach (string row in rows)
{
    if (string.IsNullOrEmpty(row)) continue;
    string[] cols = row.Split(',');
    DailyValues v = new DailyValues();

    v.Open = Convert.To*(cols[0]);
    v.High = Convert.To*(cols[1]);
    v.Low = Convert.To*(cols[2]);
    v.Close = Convert.To* (cols[3]);
    v.Volume = Convert.To* (cols[4]);
    v.AdjClose = Convert.To*(cols[5]);
    v.Date = Convert.To*(cols[6]);
    values.Add(v);


    return values;
}    

2 个答案:

答案 0 :(得分:1)

看起来您的CSV文件包含无法转换为十进制数据的数据。在调试器中运行它,并在抛出异常时查看row

如果您使用Decimal.TryParse(),返回值将告诉您转换是否成功而没有抛出异常。

编辑:

作为TryParse的一个例子:

Decimal _Open, _High;
if (!Decimal.TryParse(cols[0], out _Open))
{
    Debug.Print("Error on row: {0}", row);
    continue;
}
v.Open = _Open;

if (!Decimal.TryParse(cols[1], out _High))
{
    Debug.Print("Error on row: {0}", row);
    continue;
}
v.High = _High;

答案 1 :(得分:0)

您可以点击此链接从csv文件中读取数据: http://www.codeproject.com/Questions/393163/Csharp-Reading-from-a-CSV-file

相关问题