Search code examples
c#csvasp.net-core-2.0

Is there a way to deserialize CSV to object, mapping by varied column names?


I would like to deserialize CSVs to objects, mapping by varied column names, as illustrated by the following examples:

Input 1
Id;Name;Document
1;Matheus;555777
2;Clarice;567890

Input 2
"Id_Person";"First_Name";"Phone"
3;"John";"999-9999"

public class People
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public string Doc { get; set; }
}

Note that the column names change by file, and a column can even be missing.

I would like to map "Id" and "Id_Person" to the PersonId property, and so on.

How to do it?


Solution

  • Actually found something that solved my problem: CsvHelper

    Setting up:

    public sealed class PessoaCSVMap : ClassMap<Pessoas>
    {
        public PessoaCSVMap()
        {
            Map(m => m.NomeCompleto).Name("Nome", "Name");
            Map(m => m.Documento).Name("Documento", "Doc", "CPF");
            Map(m => m.Email1).Name("Email", "Email1", "E-mail", "E-mail1");
            Map(m => m.PessoaId).Ignore();
        }
    }
    

    Using:

    const string CSV = "Nome;Email;bleu\nMatheus;matheus.lacerda@email.com.br;blau\nClarice;null;null";
    CsvReader csv = new CsvReader(new StringReader(CSV));
    csv.Configuration.RegisterClassMap<PessoaCSVMap>();
    csv.Configuration.Delimiter = ";";
    csv.Configuration.HeaderValidated = null;
    csv.Configuration.MissingFieldFound = null;
    List<Pessoas> pessoas = csv.GetRecords<Pessoas>().ToList();