Search code examples
c#.netcsvcsvhelper

Convert or filter members in CsvHelper when writing


Imagine I have a class like this

public class DataGroup 
{
    public string DataA { get; set; }
    public string DataB { get; set; }
    public bool Updated { get; set; }
}

I need to write an empty string or "N/A" for DataA and DataB when Updated == false, and the actual value when Updated == true;

Is this possible with CsvHelper?

Type conversion does not seem to work as it only access the final member so it is not able to read the value of Updated.

There is a Conversion method for the MapMember class but it seems to only work for reading.


Solution

  • You can use the Convert method. This method can be a little confusing because it can either ConvertFromString or ConvertToString, depending on how you use it.

    ConvertFromString Use Row with CsvReader

    Map(m => m.DataA).Convert(m => m.Row.GetField("DataA") + m.Row.GetField("Updated"));
    

    ConvertToString Use Value with CsvWriter

    Map(m => m.DataA).Convert(m => m.Value.DataA + m.Value.Updated);
    

    You want ConvertToString, so your ClassMap could be something like this.

    public class DataGroupMap : ClassMap<DataGroup>
    {
        public DataGroupMap()
        {
            Map(m => m.DataA).Convert(m =>
            {
                if (m.Value.Updated) { return m.Value.DataA; }
                return "N/A";
            });
            Map(m => m.DataB).Convert(m =>
            {
                if (m.Value.Updated) { return m.Value.DataB; }
                return "N/A";
            });
            Map(m => m.Updated);
        }
    }