I'm trying to generate CSV file based on Model where one of the properties is list. So, my goal is to specify some list of properties and generate fields and values based on this properties. As an example, result can be like:
Attribute:Brand | Attribute:Brand | Attribute:Size | Attribute:Brand |
---|---|---|---|
Test Value1 | Test Value2 | Test Value3 | Test Value4 |
I was trying and fail with anonymous objects or model objects.
Basically, there are two challenges:
Any idea/advise of how it can be resolved? What will be better to use anonymous object or model?
Note: I don't need to read it at all. I just need to save it.
This is one way you could do it.
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; }
}