Search code examples
c#listcsvinitializationinitializer-list

How to import csv into List<object> in C#


I am creating a List object with the folowing class:

public class Item
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
    public string D { get; set; }
    public int E { get; set; }
}

Like so:

public List<Item> Flower = new List<Item>{};

How would I go about initializing this list with the contents of a csv file that is structured like so?

A,B,C,D,1

Solution

  • Something like...

    var listOfObjects = File.ReadLines( "theFile.csv" ).Select( line => new Item( line ) ).ToList();
    

    and

     class Item
     {
         public Item( string line )
         {
             var split = line.Split(',');
             A = split[0];
             B = split[1];
             C = split[2];
             D = split[3];
             E = int.Parse( split[4] );
         }
    
         // [...]
     }
    

    and add some error handling, of course...