user1765603
user1765603

Reputation: 137

CSVHelper - Mapping CSV with variable header to object

I'm trying to map some variable-format tab-separated files to my class, Foo:

public class Foo
{
    public string A { get; set; }
    public int? B { get; set; }
    public double? C { get; set; }
}

File 1:

A   B   C
string  1   1.0

File 2:

Bee Sea
1   1.0

When the header format is constant, this is easy to do with CsvHelper using a CsvClassMap:

public sealed class FooMap : CsvClassMap<Foo>
{
    public FooMap()
    {
        Map(x => x.A).Name("A");
        Map(x => x.B).Name("B");
        Map(x => x.C).Name("C");
    }
}

However, this becomes complex when the header format is variable.

What would be the best way of mapping to this object?

I imagine I will be populating a mapping table for headers to properties with a unique key on the headers column, then looking up each header's respective property.

Current direction of investigation:

public sealed class FooMap : CsvClassMap<Foo>
{
    public FooMap()
    {
    }

    public void SetHeaders(List<string> headers)
    {
        var dictionary = new Dictionary<string, List<string>>();
        dictionary.Add("A", new List<string>() { "A", "Aay" });
        dictionary.Add("B", new List<string>() { "B", "Bee" });
        dictionary.Add("C", new List<string>() { "C", "Sea" });

        ...

    }
}

Upvotes: 1

Views: 5012

Answers (1)

Josh Close
Josh Close

Reputation: 23373

You can specify multiple names per property and make it not throw an exception if there is a missing field.

Here is an example using LINQPad:

void Main()
{
    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream))
    using (var reader = new StreamReader(stream))
    using (var csv = new CsvReader(reader))
    {
        writer.WriteLine("A Bee C");
        writer.WriteLine("string    1   1.0");
        writer.Flush();
        stream.Position = 0;

        csv.Configuration.Delimiter = " ";
        csv.Configuration.WillThrowOnMissingField = false;
        csv.Configuration.RegisterClassMap<FooMap>();
        csv.GetRecords<Foo>().ToList().Dump();
    }
}

public class Foo
{
    public string A { get; set; }
    public int? B { get; set; }
    public double? C { get; set; }
    public Guid? D { get; set; }
}

public class FooMap : CsvClassMap<Foo>
{
    public FooMap()
    {
        Map( m => m.A ).Name( "A", "Aay" );
        Map( m => m.B ).Name( "B", "Bee" );
        Map( m => m.C ).Name( "C", "Sea" );
        Map( m => m.D ).Name( "D", "Dee" );
    }
}

The result:

A: string
B: 1
C: 1
D: null

Upvotes: 3

Related Questions