Processing CSV File

杀马特。学长 韩版系。学妹 提交于 2021-02-10 16:15:37

问题


I am using Sebastien LorionReference CSV reader to process my CSV file in C# 3.0.

Say example

id|name|dob (Header)
1|sss|19700101 (data)
2|xx|19700201  (data)

My Business Object is

class Employee
{
   public string ID {get;set;}
   public string Name {get;set;}
   public string Dob {get;set;}
}

I read the CSV stream and stored it in List<string[]>

List<string[]> col = new List<string[]>();

using (CsvReader csv = new CsvReader
               (new StreamReader("D:\\sample.txt"), true, '|'))
{
    col = csv.ToList();
}

How to iterate over the list to get each Employee like

     foreach (var q in col)
    {
        foreach (var r in q)
        {
            Employee emp=new Employee();
            emp.ID =r[0];
            emp.Name=r[1];
            emp.Dob=r[2];
        }
    }

If i call r[0],r[1],r[2] i am getting "index out of range exception".How the process the list to avoid the error?

Edit

Sorry I got the result. When i process

 foreach (var q in col)
{

        Employee emp=new Employee();
        emp.ID =q[0];
        emp.Name=q[1];
        emp.Dob=q[2];

}

things work fine.


回答1:


The correct way to read such a reader would be, for example:

List<Employee> employees = new List<Employee>();
using (IDataReader csv = new CsvReader
             (new StreamReader("D:\\sample.txt"), true, '|'))
{
    while(csv.Read()) {
        Employee emp = new Employee();
        emp.ID = r.GetString(0); // or int.Parse(...) if it is an int
        emp.Name = r.GetString(1);
        emp.Dob = r.GetString(2); // or DateTime.Parse(...) if it is a DateTime
        employees.Add(emp);
    }
}

You could also use an iterator block, and you might be able to use GetDateTime / GetInt32, but I couldn't say for sure so I've just used GetString in the above.



来源:https://stackoverflow.com/questions/2617433/processing-csv-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!