Mapping an IEnumerable property with CSVHelper

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.


I know this an old question but I have created another solution by putting the following property on my DTO (User class).

public string ConcatenatedUserNumbers
    {
        get
        {
            if (ContactNumbers != null && ContactNumbers.Any())
            {
                return string.Join("; ", ContactNumbers.Select(a => a.Number));
            }
            return string.Empty;
        }
    }

I then just map to this property in CsvHelper like so:

Map(a => a.ConcatenatedUserNumbers).Name("User Numbers");

You could obviously do the same for user types, or have a method that gets both. The data may not be perfect but the end user can still use the 'filter' functionality within excel and it will be human readable. All without the need for excess mappings etc.

Note: If this extra property is only for a CSV mapping you could also make a class CSVUser : User. You would put the suggested property on CSVUser only.

I hope this helps somebody out.