7

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?

0

2 Answers 2

10

Set MyValue to be optional.

public sealed class MyItemMap : ClassMap<MyItem>
{
    public MyItemMap()
    {
        Map(m => m.Id);
        Map(m => m.MyValue).Optional();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

5

Add [Optional] attribute to MyValue in MyItem class.

It avoids to create the mapper class

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

    [Optional]
    public int? MyValue { get; set; }
} 

1 Comment

Better answer IMHO

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.