Dynamically create property based on if CSV has corresponding header using CSV Helper library

2k Views Asked by At

Using CSV Helper, I'm wondering if there is there a way to dynamically create class properties based on whether or not the corresponding column is found in my csv file.

The file I'm working with may or may not have a column titled 'ACTIVITY'. If upon reading it, there is no such column, is there a way to omit the creation of the Activity property all together?

// csv properties
public class Pr530CsvHandler
{
  public string Company { get; set; }
  public string Name { get; set; }

  // other expected properties...

  public string Activity { get; set; }  //<-- don't create if there is no corresponding column in CSV
}

// map
public sealed class Pr530Map : ClassMap<Pr530CsvHandler>
{
  public Pr530Map()
  {
    Map(m => m.Company).Name("COMPANY").Optional();
    Map(m => m.Name).Name("NAME").Optional();

    // other mapped headers...

    Map(m => m.Activity).Name("ACTIVITY").Optional();  // this one may not exist in CSV
  }
}

1

There are 1 best solutions below

0
David Specht On BEST ANSWER

You could just get a list of dynamic objects.

using (var reader = new StreamReader("path\\to\\file.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    var records = csv.GetRecords<dynamic>();
}

Otherwise, there isn't a way to dynamically create a property on a regular class. You could instead have 2 different classes, one with and one without the Activity property and load the correct one depending on the header.

void Main()
{
    using (var reader = new StreamReader("path\\to\\file.csv"))
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        csv.Context.RegisterClassMap<Pr530ActivityMap>();
        csv.Context.RegisterClassMap<Pr530Map>();
        csv.Read();
        csv.ReadHeader();
        
        if (csv.HeaderRecord.Contains("ACTIVITY"))
        {
            var records = csv.GetRecords<Pr530ActivityCsvHandler>();
        }
        else 
        {
            var records = csv.GetRecords<Pr530CsvHandler>();
        }       
    }
}

public sealed class Pr530Map : ClassMap<Pr530CsvHandler>
{
    public Pr530Map()
    {
        Map(m => m.Company).Name("COMPANY").Optional();
        Map(m => m.Name).Name("NAME").Optional();
        // other mapped headers...
    }
}

public sealed class Pr530ActivityMap : ClassMap<Pr530ActivityCsvHandler>
{
    public Pr530ActivityMap()
    {
        Map(m => m.Company).Name("COMPANY").Optional();
        Map(m => m.Name).Name("NAME").Optional();
        // other mapped headers...
        Map(m => m.Activity).Name("ACTIVITY").Optional();
    }
}

public class Pr530ActivityCsvHandler
{
    public string Company { get; set; }
    public string Name { get; set; }
    public string Activity { get; set; }
}

public class Pr530CsvHandler
{
    public string Company { get; set; }
    public string Name { get; set; }
}