Search code examples
c#.netcsv.net-corecsvhelper

CSVHELPER Conditionally ignore writing fields when values null or empty


Im currently writing a flattened DTO object to CSV using the csvhelper's csvwriter. Is there a way to conditionally ignore certain fields if they havent yet been initialised or are null in the mapper ? I see the ignore flag takes a boolean , but how would i get access to the field in question to test for this.

Apologies if this has been answered elsewhere but have searched both teh github issues aswell as stackoverflow.


Solution

  • The answer for me, was to pass in a collection of fields/columns to ignore into the mapper. This involved me checking the data collection for any empty values on all rows, if so then i can omit that column completely. Then i pass this requiredFields collection into the mapper like so .

    public sealed class ApplicationCsvWriterMap : ClassMap<ApplicationDto>
    {
        public ApplicationCsvWriterMap(List<string> requiredFields)
        {
            Map(m => m.Id).Index(1).Name("AppId").Ignore(!requiredFields.Contains("id"));
            Map(m => m.Status.Text).Index(2).Name("Status").Ignore(!requiredFields.Contains("status"));
            Map(m => m.ApplicationTimestamp).Index(3).Ignore(!requiredFields.Contains("applicationTimestamp"));
            Map(m => m.LastModified).Index(4).Ignore(!requiredFields.Contains("lastModified"));
    

    Then I can setup the mapper like so , passing in the requiredFields collection like so

      else if (results.Data is List<Application> applications)
                {
                    csvWriter.Configuration.RegisterClassMap(new ApplicationCsvWriterMap(results.RequiredFields));
                    csvWriter.WriteRecords(_dtoMapper.MapApplications(applications));
                }