Click here to Skip to main content
15,902,845 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was looking for a sufficient answer for quite some time but didn't have any luck.

As the title suggest, I am trying to read CSV data to the list. Basically I have a class called Person:

C#
public string Name { get; set; }
public string Surname { get; set; }
public DateTime DateOfBirth { get; set; }


I am trying to read it from the CSV to the List. I'm not sure how to do that in terms of the rows so that it will match the name, surname, dob

The CSV file looks like that:

Name Surname Date Of Birth
Angela Blah 24/01/1990


In short, I want the 'Angela' details to be inserted in the List of Person object.

What I have tried:

I did tried few things:

Create a constuctor in my Person class:

C#
 public Person(string line) 
{ 
        var split = line.Split(',');
        Name = split[0];
        Surname = split[1];
        DateOfBirth = split[2];  
}


Then wanted to use it like that:

C#
var people = File.ReadLines("../people.csv").Select(line => new 
             Person(line)).ToList();


But of course it is empty because I am creating a new person. This is closest of what I could think of...is it the right direction for an answer or is it completely wrong?
Posted
Updated 3-Dec-17 10:11am

1 solution

The first thing to note is that your sample data doesn't match your code: it contains no commas, so the Split won't work.
Then, you need to use DateTime.TryParse or DateTime.TryParseExact to convert the string to a DateTime.

Other than that and the wrong method name (it should be File.ReadAllLines) that code should work - but you should check the results of the Split operation to ensure the line did contain at least three items separated by commas.
 
Share this answer
 
Comments
Richard Deeming 5-Dec-17 11:17am    
There's nothing wrong with File.ReadLines[^], and it's probably a better choice than ReadAllLines in this case. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900