在从 CsvHelper GetRecords 返回的动态对象中包含 RawRecord

Include RawRecord in dynamic objects returned from CsvHelper GetRecords

我通过使用 Configuration.RegisterClassMap 转换为 Class 对象时可以正常工作(本质上我正在将 row.Context.RawRecord 映射到 属性 Class 称为 RawRecord):

public sealed class RecordMap : ClassMap<CsvRecord>
{
    public RecordMap()
    {
        AutoMap(CultureInfo.CurrentCulture);
        Map(m => m.RawRecord).ConvertUsing(row => row.Context.RawRecord.Replace("\r\n", ""));
    }
}

...但我不想使用 Class 对象(在本例中为 CsvRecord),而是使用带有 csv.GetRecords<dynamic>() 的动态对象。这对我有用,除了我无法弄清楚如何获得 RawRecord。理想情况下,如果我可以添加一些配置以简单地将其添加为动态对象上的新列,但我找不到类似的东西。

我正在使用 linq 构建域对象列表 (Individuals),其中包括对 CSV 行进行分组,因此我不想手动遍历每条记录:

using (var csv = new CsvReader(reader, CultureInfo.CurrentCulture))
{
    csv.Configuration.PrepareHeaderForMatch = (string header, int index) => Regex.Replace(header, "[^A-Za-z0-9]", "");

    var dateUpdated = DateTime.UtcNow;
    var individuals = csv.GetRecords<dynamic>().ToList().Where(r => r.GroupType == "Individual").
        GroupBy(r => r.GroupID).
        Select(g => new Individual(
            // Include constructor arguments here
            g.Key,
            g.First().Name1
            // ...
            // Include an array of all raw CSV records that have been used to generate this object
            // This currently fails
            g.Select(r => r.RawRecord).Cast<string>().ToArray()
        )).ToList();
}

我认为没有办法通过配置来完成。

using (var csv = new CsvReader(reader, CultureInfo.CurrentCulture))
{
    csv.Configuration.PrepareHeaderForMatch = (string header, int index) => Regex.Replace(header, "[^A-Za-z0-9]", "");

    csv.Read();
    csv.ReadHeader();

    var records = new List<dynamic>();

    while (csv.Read())
    {
        var record = csv.GetRecord<dynamic>();
        record.RawRecord = csv.Context.RawRecord.Replace("\r\n", "");
        records.Add(record);
    }

    var dateUpdated = DateTime.UtcNow;
    var individuals = records.Where(r => r.GroupType == "Individual").
        GroupBy(r => r.GroupID).
        Select(g => new Individual(
            // Include constructor arguments here
            g.Key,
            g.First().Name1
            // ...
            // Include an array of all raw CSV records that have been used to generate this object
            // This currently fails
            g.Select(r => r.RawRecord).Cast<string>().ToArray()
        )).ToList();
}