CSV to object model mapping

Viewed 58061

I have a CSV file that I want to read into a List. Here's an example file:

Plant,Material,"Density, Lb/ft3",Storage Location
FRED,10000477,64.3008,3300
FRED,10000479,62.612,3275
FRED,10000517,90,3550
FRED,10000517,72,3550
FRED,10000532,90,3550
FRED,10000532,72,3550
FRED,10000550,97,3050

I know I can manually read in the CSV file and build the list using a normal StreamReader, but I was wondering if there was a better way, perhaps using LINQ?

6 Answers

With Cinchoo ETL library, can parse CSV file into objects

Define type matching CSV file structure as below

public class PlantType
{
    public string Plant { get; set; }
    public int Material { get; set; }
    public double Density { get; set; }
    public int StorageLocation { get; set; }
}

Load the CSV file

static void LoadCSV()
{
    using (var p = new ChoCSVReader<PlantType>("*** YOUR CSV FILE PATH ***")
        .WithFirstLineHeader(true)
        )
    {
        foreach (var rec in p)
        {
            Console.WriteLine(rec.Dump());
        }
    }
}

It doesn't use LINQ but CsvHelper is a simple method to implement CSV parsing to a .NET object:

using (TextReader txt = new StreamReader(filename))
{
    using (var csv = new CsvReader(txt))
    {
        var records = csv.GetRecords<PlantMaterial>();
        return records.ToList();
    }
}
Related