Home > OS >  Map numbered columns from a CSV file to an array with CsvHelper
Map numbered columns from a CSV file to an array with CsvHelper

Time:09-25

I have a CSV file with columns that follow a numbered logic: enter image description here

So I want to store Leds values in an collection. To do so I created the following ClassMap:

public class EyeExcitation
{
    public int Dt { get; set; }
    public double[] Leds { get; set; } = new double[6];
}

sealed class EyeExcitationMap : ClassMap<EyeExcitation>
{
    public EyeExcitationMap()
    {
        Map(m => m.Dt).Name("Dt");
        Map(m => m.Leds[0]).Name("LED1 R");
        Map(m => m.Leds[1]).Name("LED2 R");
        Map(m => m.Leds[2]).Name("LED3 R");
        Map(m => m.Leds[3]).Name("LED4 R");
        Map(m => m.Leds[4]).Name("LED5 R");
        Map(m => m.Leds[5]).Name("LED6 R");
    }
}

But when I registerthe the ClassMap with

csv.Context.RegisterClassMap<EyeExcitationMap>();

I got this exception :

System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'
Inner Exception
InvalidOperationException: No members were found in expression '{expression}'.

I think it's because of the indexes.
Do you know how to do it?

CodePudding user response:

You will need to use Convert.

sealed class EyeExcitationMap : ClassMap<EyeExcitation>
{
    public EyeExcitationMap()
    {
        Map(m => m.Dt).Name("Dt");
        Map(m => m.Leds).Convert( args => {
            var leds = new double[6];
            for (int i = 0; i < 6; i  )
            {
                leds[i] = args.Row.GetField<double>($"LED{i   1} R");
            }
            return leds;
        });
    }
}

CodePudding user response:

Not sure if it is the best way, but it works:

sealed class EyeExcitationMap : ClassMap<EyeExcitation>
{
    public EyeExcitationMap()
    {
        Map(m => m.Dt).Name("Dt");
        Map(m => m.Leds).Convert(args =>
        {
            double[] Leds = new double[6];
            Leds[0] = args.Row.GetField<double>("LED1 R");
            Leds[1] = args.Row.GetField<double>("LED2 R");
            Leds[2] = args.Row.GetField<double>("LED3 R");
            Leds[3] = args.Row.GetField<double>("LED4 R");
            Leds[4] = args.Row.GetField<double>("LED5 R");
            Leds[5] = args.Row.GetField<double>("LED6 R");
            return Leds;
        });
    }
}
  • Related