Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading CSV with optional column using CsvHelper

Tags:

c#

csvhelper

I want to read a CSV file that has some optional columns, for that I have defined a class with optional property using "?" but can't make it work.

public class MyItem
{
    public int Id { get; set; }
    public int? MyValue { get; set; }
}

The mapping class:

public sealed class MyItemMap : ClassMap<MyItem>
{
    public MyItemMap()
    {
        Map(m => m.Id);
        Map(m => m.MyValue);
    }
}

And then a console app:

static void Main(string[] args)
{
    using (var reader = new StreamReader(@"C:\Test2Delete\ConsoleAppCSV\MyItem.csv"))
    using (var csv = new CsvReader(reader))
    {
        csv.Configuration.RegisterClassMap(new MyItemMap());
        csv.Configuration.HeaderValidated = null;
        try
        {
            var records = csv.GetRecords<MyItem>();
            foreach (var r in records)
            {
                Console.WriteLine(r.Id + " " + r.MyValue);
            }

            Console.ReadLine();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.ReadLine();
        }
    }
}
}

So I want to be able to read files that contain "Id", "MyValue" columns and also files with only "Id" column. How can I achieve this?

like image 654
Bonomi Avatar asked Jul 18 '26 12:07

Bonomi


1 Answers

Set MyValue to be optional.

public sealed class MyItemMap : ClassMap<MyItem>
{
    public MyItemMap()
    {
        Map(m => m.Id);
        Map(m => m.MyValue).Optional();
    }
}
like image 122
David Specht Avatar answered Jul 20 '26 08:07

David Specht



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!