【问题标题】:Export nested object to CSV将嵌套对象导出到 CSV
【发布时间】:2020-07-03 19:07:59
【问题描述】:

我正在使用 CsvHelper 库将数据导出到 CSV。我在为嵌套列表对象创建地图时遇到了困难。

public class Level1
{
    public int Prop1 { get; set; }
    public string Prop2 { get; set; }
    public Level2 Level2 { get; set; }
}

public class Level2
{
    public int Prop3 { get; set; }
    public string Prop4 { get; set; }
    public List<Level3> Level3 { get; set; }
}
public class Level3
{
    public int Prop5 { get; set; }
}

作为 csv 的输出,想要的是:

Prop1,Prop2,Prop3,Prop4,Level3
  1  ,test ,2    , LL, , <list as ; separated>

谁能帮助我使用 CsvHelper 库创建地图?

【问题讨论】:

    标签: c# .net export-to-csv csvhelper


    【解决方案1】:

    对于嵌套列表,您可以使用string.Join() 连接prop5,如以下代码:

    List<Level1> levels = new List<Level1>();
    var result = levels.Select(x => new
    {
        Prop1 = x.Prop1,
        Prop2 = x.Prop2,
        Prop3 = x.Level2.Prop3,
        Prop4 = x.Level2.Prop4,
        Level3 = string.Join(";", x.Level2.Level3.Select(y => y.Prop5))
    }).ToList();
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-05-07
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      相关资源
      最近更新 更多