Sai Krishna
Sai Krishna

Reputation: 85

Map different Column Header Names to a single field in the C# entity class using CsvHelper

I have a couple different csv file structures each having a different column Header name on the column 2 and need to map this column values to the field on the c# entity class and was wondering how i can achieve this using CsvHelper.

Ex: one file will have column Header as "ColumnXYZ" and another file will have column Header as "ColumnABC" and using the CsvHelper will have to first check which column Header name exists on the file and then map the column values to "FieldQwe" of an entity. Both Column Header names will not exist on single file. So looking for any thoughts on handling this scenario.

Can i use something like this on the entity field so the AutoMap works just fine?

[Name("ColumnABC", "ColumnXYZ")]
public string Field1{ get; set; }

Upvotes: 1

Views: 2955

Answers (2)

adinas
adinas

Reputation: 4550

You can use a tag helper

public class Foo
{
    [CsvHelper.Configuration.Attributes.Name("TheId")]
    public int Id { get; set; }
    [CsvHelper.Configuration.Attributes.Name("TheName")]
    public string Name { get set; }
}

See This

Upvotes: 2

David Specht
David Specht

Reputation: 9044

You can find some configuration examples at https://joshclose.github.io/CsvHelper/examples/configuration/class-maps

void Main()
{
    using (var reader = new StreamReader("path\\to\\file.csv"))
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        csv.Configuration.RegisterClassMap<FooMap>();
        var records = csv.GetRecords<Foo>();
    }
}

public class Foo
{
    public int Id { get; set; }
    public string Name { get set; }
}

public sealed class FooMap : ClassMap<Foo>
{
    public FooMap()
    {
        Map(m => m.Id).Name("TheId", "Id");
        Map(m => m.Name).Name("TheName", "Name");
    }
}

Upvotes: 3

Related Questions