How to write IList<T> to csv file using CsvHelper?

霸气de小男生 提交于 2021-01-29 04:24:27

问题


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 CsvClassMaps 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!