CsvHelper - read in multiple columns to a single list

前端 未结 4 565
梦如初夏
梦如初夏 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:04

    This does the trick as a mapper.

    public sealed class PersonMap : CsvClassMap
    {
        private List attributeColumns = 
            new List { "Attribute1", "Attribute2", "Attribute3" };
    
        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 =>
                attributeColumns
                    .Select(column => row.GetField(column))
                    .Where(value => String.IsNullOrWhiteSpace(value) == false)
                );
        }
    }
    

    Then you just need something like this

    using (var reader = new CsvReader(new StreamReader(filePath)))
    {
        reader.Configuration.RegisterClassMap();
        while (reader.Read())
        {
            var card = reader.GetRecord();
        }
    }
    

提交回复
热议问题