CsvHelper-将多列读入单个列表 [英] CsvHelper - read in multiple columns to a single list
本文介绍了CsvHelper-将多列读入单个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 CSVHelper 读取大量数据
I'm using CSVHelper to read in lots of data
我想知道是否有可能读取其中的最后 n
列并将其转置为列表
I'm wondering if it's possible to read the last n
columns in and transpose them to a list
"Name","LastName","Attribute1","Attribute2","Attribute3"
并将数据模制成这样的东西
And mould the data into something like this
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public IList<string> Attributes { get; set; }
}
我想一步一步做到这一点,我敢肯定我可以有一个中间步骤,将一个具有匹配属性属性的对象放入其中,但是最好一次完成
I'm looking to do this in one step, I'm sure I could have an intermediate step where I put into an object with matching attribute properties but it would be nice to do it on a one-er
推荐答案
这可以作为映射器来解决。
This does the trick as a mapper.
public sealed class PersonMap : CsvClassMap<Person>
{
private List<string> attributeColumns =
new List<string> { "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<string>(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<PersonMap>();
while (reader.Read())
{
var card = reader.GetRecord<Person>();
}
}
这篇关于CsvHelper-将多列读入单个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文