Wellspring Wellspring - 1 year ago 227
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


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

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

Answer Source

You have to manually convert the column like below.

Map(x => x.Price)
    .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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download