-3

I have a CSV file with the following format: first name, last name, date of birth, date of death. How can i get all the datas from my CSV file and convert them into an object list?

I was thinking about implementing the following class

public class Person
{
    private string f_name;
    private string l_name;
    private int dob;
    private int dod;

    public Person(string first, string second, int dob, int dod)
    {
        this.f_name = first;
        this.l_name = second;
        this.dob = dob;
        this.dod = dod;
    }
}
Gusti
  • 71
  • 2
  • 11
  • It is so sad that there are so many CSV parsing questions, where most of the answers rely on simple string splitting. **This is wrong**. Use a CSV parsing library. – CodeCaster Mar 11 '16 at 11:17

1 Answers1

-1
    List<Person> result = File.ReadAllLines("@C:\file.csv")
        .Select(y => y.Split(','))
                        .Select(x => new {
                            first = x[0],
                            second = x[1],
                            dob=int.Parse(x[2]),
                            dod =int.Parse(x[3]))
                            }).Select(x=> new Person(x.first, x.second, x.dob, x.dod ))
                           .ToList();

inspired from this answer

Community
  • 1
  • 1
asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84
  • 1
    CSV files may use quotes ( " ) for string values, multi-line string values may exist too. This sample is very simple and suitable only for simple/specific tasks, when you "trust" incoming file. – Dmitry Mar 11 '16 at 10:58