CsvHelper - read in multiple columns to a single list

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

    I don't know this library, so following might be helpful or not.

    If you already have an IEnumerable> which represents all records with all columns you could use this Linq query to get your List with the IList Attributes:

    IEnumerable> allRecords = .....;
    IEnumerable allPersons = allRecords
    .Select(rec => 
    {
        var person = new Person();
        person.FirstName = rec.ElementAt(0);
        person.LastName = rec.ElementAtOrDefault(1);
        person.Attributes = rec.Skip(2).ToList();
        return person;
    }).ToList();
    

    Edit: Downloaded the library, following at least compiles, could not really test it:

    IList allPersons = new List();
    using (var reader = new CsvHelper.CsvReader(yourTextReader))
    {
        while (reader.Read())
        {
            var person = new Person();
            person.FirstName = reader.CurrentRecord.ElementAt(0);
            person.LastName = reader.CurrentRecord.ElementAtOrDefault(1);
            person.Attributes = reader.CurrentRecord.Skip(2).ToList();
            allPersons.Add(person);
        }
    }
    

提交回复
热议问题