Export nested object to CSV

I’m using CsvHelper library to export data to CSV. I’m facing a difficulty on creating a map for the nested list object.

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; } } 

As an output of the csv what want to have is:

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

Can anyone help me out on creating the map using CsvHelper library?

Add Comment
1 Answer(s)

For nested list, you could use string.Join() to concatenate prop5, like the following code :

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(); 

I hope you find this helpful.

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.