【问题标题】:CsvHelper - How to map by index the whole row to a model memberCsvHelper - 如何通过索引将整行映射到模型成员
【发布时间】:2021-06-26 16:03:03
【问题描述】:

我正在开发一个 C# Windows 服务,该服务使用 CsvHelper 及其按索引的类映射功能将 csv 文件读入列表。我想在每个模型中存储原始原始数据行。

我尝试过使用 Map(m => m.Row).Index(-1);但这没有用。我也尝试过 ConvertUsing,但我收到一条消息,指出 MemberMap 不包含“ConvertUsing”的定义。

RegisterClassMap 和 csv.GetRecords 功能正在执行批量读取,我没有机会捕获原始原始数据行。

任何帮助将不胜感激。我需要创建一封电子邮件,其中包含状态(将数据发送到微服务)和原始原始数据两个,并且希望在 CsvHelper 读取文件时存储它。

【问题讨论】:

    标签: c# csvhelper


    【解决方案1】:
    void Main()
    {
        var s = new StringBuilder();
        s.Append("Id,Name\r\n");
        s.Append("1,one\r\n");
        var config = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
        };
        using (var reader = new StringReader(s.ToString()))
        using (var csv = new CsvReader(reader, config))
        {
            csv.Context.RegisterClassMap<FooMap>();
            csv.GetRecords<Foo>().ToList().Dump();
        }
    }
    
    private class Foo
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string RawRow { get; set; }
    }
    
    private class FooMap : ClassMap<Foo>
    {
        public FooMap()
        {
            Map(m => m.Id);
            Map(m => m.Name);
            Map(m => m.RawRow).Convert(args => args.Row.Parser.RawRecord);
        }
    }
    

    .Dump() 是一个LINQPad 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 2021-01-08
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 2015-12-12
      相关资源
      最近更新 更多