CsvHelper - read in multiple columns to a single list

前端 未结 4 569
梦如初夏
梦如初夏 2020-12-14 11:18

I\'m using CSVHelper to read in lots of data

I\'m wondering if it\'s possible to read the last n columns in and transpose them to a list



        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 12:09

    You don't actually need to define the column names beforehand, you can get them from the FieldHeaders property. So in a more dynamic version of Neil's answer you could define your Mapper as such:

    public sealed class PersonMap : CsvClassMap {
        public override void CreateMap() {
            Map(m => m.FirstName).Name("FirstName").Index(0);
            Map(m => m.LastName).Name("LastName").Index(1);
            Map(m => m.Attributes).ConvertUsing(row =>
                (row as CsvReader)?.FieldHeaders
                     .Where(header => header.StartsWith("Attribute"))
                     .Select(header => row.GetField(header))
                     .Where(value => !string.IsNullOrWhiteSpace(value))
                     .ToList()
            );
        }
    }
    

提交回复
热议问题