你可以得到一个dynamic
对象列表。
using (var reader = new StreamReader("path\\to\\file.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csv.GetRecords<dynamic>();
}
否则,没有办法在常规类上动态创建属性。相反,您可以有 2 个不同的类,一个有属性,一个没有Activity
属性,并根据标题加载正确的类。
void Main()
{
using (var reader = new StreamReader("path\\to\\file.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Context.RegisterClassMap<Pr530ActivityMap>();
csv.Context.RegisterClassMap<Pr530Map>();
csv.Read();
csv.ReadHeader();
if (csv.HeaderRecord.Contains("ACTIVITY"))
{
var records = csv.GetRecords<Pr530ActivityCsvHandler>();
}
else
{
var records = csv.GetRecords<Pr530CsvHandler>();
}
}
}
public sealed class Pr530Map : ClassMap<Pr530CsvHandler>
{
public Pr530Map()
{
Map(m => m.Company).Name("COMPANY").Optional();
Map(m => m.Name).Name("NAME").Optional();
// other mapped headers...
}
}
public sealed class Pr530ActivityMap : ClassMap<Pr530ActivityCsvHandler>
{
public Pr530ActivityMap()
{
Map(m => m.Company).Name("COMPANY").Optional();
Map(m => m.Name).Name("NAME").Optional();
// other mapped headers...
Map(m => m.Activity).Name("ACTIVITY").Optional();
}
}
public class Pr530ActivityCsvHandler
{
public string Company { get; set; }
public string Name { get; set; }
public string Activity { get; set; }
}
public class Pr530CsvHandler
{
public string Company { get; set; }
public string Name { get; set; }
}