Search code examples
c#csvhelper

How to convert specific column values to lowercase


I am trying to figure it out if CsvHelper can manipulate specific column values in the CSV when reading the file.

For example, based on the setup below, I would like to receive the email values always as lowercase:

public class MyCsvEntity : ICsvEntity
{
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string DirectManager { get; set; }
    public Dictionary<string, string> DynamicColumns { get; set; }
}

Mapping:

public sealed class MyCsvMap : ClassMap<MyCsvEntity>
{
    public MyCsvMap()
    {
        Map(m => m.Email).Name("Email");
        Map(m => m.FirstName).Name("First Name");
        Map(m => m.LastName).Name("Last Name");
        Map(m => m.DirectManager).Name("Direct Manager");
    }
}

I've tried to find documentation and to look for any built-in configuration that would help me accomplish this, but to no avail. For the moment I'm reading the data exactly as it is in the .csv file, and performing the ToLower() elsewhere. If someone knows how to accomplish this with CsvHelper or provide any insight, much appreciated.


Solution

  • I think you should be able to use the Convert method on the Map for this:

    public sealed class MyCsvMap : ClassMap<MyCsvEntity>
    {
        public MyCsvMap()
        {
            Map(m => m.Email).Name("Email").Convert(row => row.GetField("Email").ToLower());
            Map(m => m.FirstName).Name("First Name");
            Map(m => m.LastName).Name("Last Name");
            Map(m => m.DirectManager).Name("Direct Manager");
        }
    }