Search code examples
c#csvienumerablecsvhelper

Mapping an IEnumerable property with CSVHelper


I have a class of User, which can have several contact numbers. I am using CsvHelper to generate a report on the users, which will create a CSV file of the User's name and contact details. Each contact number should be displayed in its own column, with the contact number's type as the column header.

Below I have my ContactNumber and User classes, as well as a UserMap class that should format my CSV file accordingly:

public class ContactNumber
{
    public string ContactType { get; set; }
    public string Number { get; set; }
}

public class User
{
    public string Name { get; set; }
    public IEnumerable<ContactNumber> ContactNumbers{ get; set;}
}

public sealed class UserMap : CsvClassMap<User>
{
    public UserMap()
    {
        Map(m => m.Name).Name("Username");
        // Incorrect Code
        Map(m => m.ContactNumbers).Name(c => c.ContactType);
    }
}

How should I be mapping the IEnumerable property of ContactNumbers to achieve my desired result?


Solution

  • It is not a duplicate of CsvHelper - read in multiple columns to a single list as this question asks how to convert from model to CSV and not the other way around. I solved this by creating an in-between model. So first you convert the original model (User) to your in between model (Contact), then map that model and create the CSV.