将嵌套对象导出到 CSV

Export nested object to CSV

我正在使用 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 库创建地图吗?

对于嵌套列表,你可以使用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();

希望对您有所帮助。