-3

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:

    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.

Any help would be appreciated. Thanks.

EDIT:

I did tried few things:

Create a constuctor in my Person class public Person(string line) { var split = line.Split(',');

        Name = split[0];
        Surname = split[1];
        DateOfBirth = split[2];  
    }

Then wanted to use it like that:

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?

morgh
  • 25
  • 6
  • I will not down vote, but please look up on the internet first. – Sean Mitchell Dec 03 '17 at 19:33
  • Is this the only type of object you need to be able to read in? Are the columns always in that exact order? If not then you probably want to look around for a good all-purpose CSV serialization library (can't vouch for this one, but it looks ok: https://www.codeproject.com/Articles/566656/CSV-Serializer-for-NET). Note that CSV parsing appears trivial, but in order to support quoted values that contain `,`s it's not entirely so. – Dylan Nicholson Dec 03 '17 at 19:46
  • The csv file is always at the exact order, the columns never change. – morgh Dec 03 '17 at 19:52
  • Well that makes things simpler - you just need a way of safely splitting up the tokens in a CSV file, remembering to allow for quotes (including `""`) and commas in values. Actually looking more closely at that link I sent you, don't use that one, it fails exactly on this point. Maybe try https://stackoverflow.com/questions/6542996/how-to-split-csv-whose-columns-may-contain – Dylan Nicholson Dec 03 '17 at 20:03
  • One comment one your "File.ReadLines(...)" idea - good, except that you'll end up with an extra Person whose fields contain the header names. So if you know there's always a header line, you should insert a `.Skip(1)` before `.Select(`. – Dylan Nicholson Dec 03 '17 at 20:13
  • Alright, thanks for that. Will try to work with that maybe I'll figure something out. – morgh Dec 03 '17 at 20:17
  • using String.Split for CSVs is very error prone. Fortunately there are many libraries that do it flawlessly and will even parse it to a collection – Ňɏssa Pøngjǣrdenlarp Dec 03 '17 at 22:06

2 Answers2

0

You could accomplish this by exporting the file as a string (File.ReadAllLines()), and then using the .Split(char splitcharacter) on the string to break it apart by the commas.

    static void Main(string[] args)
    {
        // READ FILE INTO TMP
        var tmp = "TEST,TEST1,TEST2".Split(',');
        var Name = tmp[0];
        var Surname = tmp[1];
        // ETC
    }
Sean Mitchell
  • 447
  • 2
  • 21
  • Unfortunately I've seen that sort of CSV deserialization in production software many times, and of course the moment a value is quoted (and contains a `,` in the value!), or worse, a line is missing items, or even worse an extra column is inserted, mayhem ensues... – Dylan Nicholson Dec 03 '17 at 19:48
  • Your program just has to be ready for that kind of behavior, but honestly if I had to work with a CSV, I would just use my own string to separate columns. Something that will never occur like "<(#)($)(#)>". It is excessive for large files, but for small ones it will almost guarantee data integrity. @DylanNicholson – Sean Mitchell Dec 03 '17 at 19:51
  • That's assuming you're in control of the CSV generation! And if you are, why pick CSV at all? Excel can output CSV lines with, e.g.: `"D1,D2","Something in ""quotes"" here",,`. It's a standard and if you intend to be able to read CSV files you should support it properly, and while it might be an interesting exercise to write your own parser, there are already many out there. – Dylan Nicholson Dec 03 '17 at 20:00
  • Agreed, but if the question asker asked for parsing CSV I am going to tell him how to do it. I am on your side man, but I will still answer them to the best of abilities. @DylanNicholson – Sean Mitchell Dec 03 '17 at 20:06
0

You could split the line and then add it to the list

static void(string[] args)
{
  var list = new List<Person>();
  var person = new Person();
  var arr = line.split(','); //line = "test1,test2,test3
  person.Name = arr[0];
  person.SurName = arr[1];
  person.DateOfBirth = arr[2];
  list.Add(person);
}

Ideally you will have a loop which will read each line from the csv and then split it based on the separator (,) and then inside the loop you will add the object of Person class in the list

Nishant Shrivastava
  • 389
  • 1
  • 3
  • 17