Wellspring Wellspring - 1 month ago 6
ASP.NET (C#) Question

Using CsvHelper, How to map to a second column, if the value of the first column equals 0

Is there a way to map to a second field, if the first field is less than 0?

For example, if you are mapping a csv file with columns

foo
and
bar
:

Map(m => m.Price).Name("foo");


And if the column
foo
equals 0, can we then map
Price
to the value of the
bar
column instead.

Answer

You have to manually convert the column like below.

Map(x => x.Price)
    .Name("foo")
    .ConvertUsing(row =>
    {
        var fooValue = row.GetField<decimal>("foo");

        if (fooValue == 0m)
        {
            return row.GetField<decimal>("bar");
        }
        return fooValue;
    });

That said, I don't think you should be using CsvHelper to do conditional mapping. Ideally, you'd have a mapping for your CSV model and another model you want to map to. Then have code that maps your CSV model to that other model.

Comments