CSV to object model mapping

You can use a simple code like this, which ignores the header and doesn't work with quotes, but may be sufficient for your needs.

from line in File.ReadAllLines(fileName).Skip(1)
let columns = line.Split(',')
select new
{
  Plant = columns[0],
  Material = int.Parse(columns[1]),
  Density = float.Parse(columns[2]),
  StorageLocation = int.Parse(columns[3])
}

Or you can use a library, like others suggested.


For the specific data shown in your question...

var yourData = File.ReadAllLines("yourFile.csv")
                   .Skip(1)
                   .Select(x => x.Split(','))
                   .Select(x => new
                                {
                                    Plant = x[0],
                                    Material = x[1],
                                    Density = double.Parse(x[2]),
                                    StorageLocation = int.Parse(x[3])
                                });

If you already have a type declared for your data then you can use that rather than the anonymous type.

Note that this code isn't robust at all. It won't correctly handle values containing commas/newlines etc, quoted string values, or any of the other esoteric stuff that is often found in CSV files.

Tags:

C#

Linq

Csv