【问题标题】:Map numbered columns from a CSV file to an array with CsvHelper使用 CsvHelper 将 CSV 文件中的编号列映射到数组
【发布时间】:2021-11-17 22:57:19
【问题描述】:

我有一个 CSV 文件,其中的列遵循编号逻辑:

所以我想将 Leds 值存储在一个集合中。为此,我创建了以下 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");
    }
}

但是当我注册 ClassMap 时

csv.Context.RegisterClassMap<EyeExcitationMap>();

我遇到了这个异常:

System.Reflection.TargetInvocationException: '调用的目标已抛出异常。'
内部异常
InvalidOperationException:在表达式“{表达式}”中找不到成员。

我认为是因为索引。
你知道怎么做吗?

【问题讨论】:

    标签: c# dictionary csvhelper


    【解决方案1】:

    您需要使用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;
            });
        }
    }
    

    【讨论】:

      【解决方案2】:

      不确定这是否是最好的方法,但它有效:

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

      【讨论】:

      • 是的,你打败了我。除了使用Convert,我认为没有其他方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多