P0DD3R5
P0DD3R5

Reputation: 336

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.

Upvotes: 1

Views: 5190

Answers (2)

P0DD3R5
P0DD3R5

Reputation: 336

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));
            }

Upvotes: 5

David Specht
David Specht

Reputation: 9074

I was a little bit confused by the question, because Ignore is all or nothing. You can't ignore a field line by line. You either include the field or you don't. You could ignore a field if say all of the records had a null or empty value for a particular member variable.

public static void Main(string[] args)
{    
    var records = new List<Foo> { new Foo { Id = 1, Name = "" }, new Foo { Id = 2 } };

    using (var csv = new CsvWriter(Console.Out))
    {        
        var shouldIgnoreName = records.All(foo => string.IsNullOrEmpty(foo.Name));

        var classMap = new DefaultClassMap<Foo>();
        classMap.AutoMap();
        classMap.Map(m => m.Name).Ignore(shouldIgnoreName);

        csv.Configuration.RegisterClassMap(classMap);
        csv.WriteRecords(records);
    }

    Console.ReadKey();
}

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}        

Upvotes: 3

Related Questions