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?
Set MyValue
to be optional.
public sealed class MyItemMap : ClassMap<MyItem>
{
public MyItemMap()
{
Map(m => m.Id);
Map(m => m.MyValue).Optional();
}
}