开发者

Processing CSV File

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜