-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; } } 
1
  • 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. Commented Mar 11, 2016 at 11:17

1 Answer 1

-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

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.