问题
I just started playing with the CsvHelper component by Josh Close. But I haven't yet fully understood the concept of mapping. What I have is a class Order
that looks like this:
public class Order
{
public int Id { get; set; }
public IList<Address> Addresses { get; set; }
}
where Address
looks like this:
public class Address
{
public string Name { get; set; }
public string City { get; set; }
}
Now I'd like to write these classes to a csv file. Sample output could be something like this:
Order.Id;Order.Address.Name;Order.Address.City
1;"Bob Miller";"London"
I have two mapping classes OrderMap
and AddressMap
:
public sealed class OrderMap : CsvClassMap<Order>
{
public OrderMap ()
{
Map (m => m.Id);
Map (m => m.Addresses).Index (0);
}
}
public sealed class AddressMap : CsvClassMap<Address>
{
public AddressMap ()
{
Map (m => m.Name);
Map (m => m.City);
}
}
But that produces the following output:
Id,Addresses
1,CsvHelperClassMappingTest.Address
So, what am I missing here?
回答1:
To the best of my knowledge the CsvClassMap
s are used only for reading, not writing. To get the output you're looking for you simply need to map your complex Order
object to a flat object that matches the layout you want in the CSV. Define your class like so:
class FlatOrder
{
public FlatOrder(Order order)
{
Id = order.Id;
var firstAddress = order.Address[0];
AddressName = firstAddress.Name;
AddressCity = firstAddress.City;
}
public int Id { get; set; }
public string AddressName { get; set; }
public string AddressCity { get; set; }
}
Then map and write your objects:
var flatOrders = orders.Select(o => new FlatOrder(o));
csv.WriteRecords(flatOrders);
If you're feeling lazy you could even use an anonymous type instead of defining one up front.
来源:https://stackoverflow.com/questions/42491832/how-to-write-ilistt-to-csv-file-using-csvhelper