首页 > 解决方案 > Reading CSV with optional column using 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?

标签: c#csvhelper

解决方案


设置MyValue为可选。

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

推荐阅读