1

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.

2
  • Are you getting the error on some lines or all lines? Commented Apr 11, 2010 at 15:08
  • After ignoring the header ,when i process the rest of the lines Commented Apr 11, 2010 at 15:12

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow! When Jon Skeet and Marc Gravell is there you can clarify anything

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.