我正在尝试基于Model生成CSV文件,其中一个属性是列表。因此,我的目标是指定一些属性列表,并基于这些属性生成字段和值。例如,结果可以是:
属性:品牌测试值1 |
---|
这是一种方法。
void Main()
{
var records = new List<ProductCsvModel>
{
new ProductCsvModel
{
DirectCosts = 1.1M,
Attributes = new List<dynamic>
{
new { Brand = "Test1" },
new { Season = "Test2" },
new { Brand = "Test3" },
new { Custom = "Test4" }
}
}
};
using (var csv = new CsvWriter(Console.Out, CultureInfo.InvariantCulture))
{
var first = records.First();
csv.WriteHeader<ProductCsvModel>();
foreach (var item in first.Attributes)
{
PropertyInfo[] properties = item.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
csv.WriteField("Attribute:" + property.Name);
}
}
csv.NextRecord();
foreach (var record in records)
{
csv.WriteRecord(record);
foreach (var item in record.Attributes)
{
PropertyInfo[] properties = item.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
csv.WriteField(property.GetValue(item));
}
}
csv.NextRecord();
}
}
}
public class ProductCsvModel
{
public decimal DirectCosts { get; set; }
public List<dynamic> Attributes { get; set; }
}