Search code examples
c#.netcsvexport-to-csvcsvhelper

How to write the list attribute of a class in CSV using CSVHelper


Currently I have the following class structures

class Foo{
    int FooID {get;set;}
    List<Bar> Bars {get;set;};
}

class Bar{
    int BarID {get;set;}    
    string BarProperty1 {get;set;}  
    string BarProperty2 {get;set;}  
    string BarProperty3 {get;set;}
}

Now I want to write a CSV file which has a field "ID" which is a mix between the ID of the Foo and Bars ID and the rest should be the properties of the Bar object.

This are some example objects:

Foo01 ID = 01
List bars = {A, Red, Red, Green; B, Yellow, Red, Red}

Foo02 ID = 02
List bars = {A, Green, Green, Red; B, Red, Purple, Orange; C, White, Black, Red}

Now the CSV writer should create a CSV looking like this:

ID;Prop1;Prop2;Prop3
01A;Red;Red;Green
01B;Yellow;Red;Red
02A;Green;Green;Red
02B;Red;Purple;Orange
02C;White;Black;Red

Is this possible with the CSVHelper or do I need to write my own implementation?


Solution

  • I have found a much easier and less complicated way of doing things:

    I basically created a new Class called CSVEntry with the required properties and looped trough my opjects to generate the desired entry before writing them to a file with CSVHelper.

            foreach (Foo foo in foos)
            {
                foreach (Bar bar in foo.bars)
                {
                    CSVEntry CSVEntry = new CSVEntry();
                    CSVEntry.id = (foo.id + bar.id);
                    CSVEntry.property1 = bar.property1;
                    CSVEntry.property2 = bar.property2;
                    CSVEntry.property3 = bar.property3;
                
                    CSVEntries.Add(CSVEntry);
                }
    
            }
    

     

        public static void writeCSVfile(List<CSVEntry> CSVEntries, String csvPath)
        {
    
            using (var streamedWriter = new StreamWriter(csvPath))
            {
    
                using (var csvWriter = new CsvWriter(streamedWriter, System.Globalization.CultureInfo.CurrentUICulture))
                {
    
                    csvWriter.WriteRecords(CSVEntries);
    
                }
    
            }
    
        }