Search code examples
c#dictionarycsvhelper

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


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?


Solution

  • 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;
            });
        }
    }