Home > Back-end >  How to write the list attribute of a class in CSV using CSVHelper
How to write the list attribute of a class in CSV using CSVHelper

Time:03-18

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?

CodePudding user response:

Unfortunately you can not directly create multiple CSV lines from a single object. So you have to flatten your list and write these into a CSV file.

Here is a working example:

public class BarMap : ClassMap<Bar>
{
    public BarMap()
    {
        Map(bar => bar.BarID).Name("Id");
        Map(bar => bar.BarProperty1).Name("Prop1");
        Map(bar => bar.BarProperty2).Name("Prop2");
        Map(bar => bar.BarProperty3).Name("Prop3");
    }
}

string content = null;

using (var memory = new MemoryStream())
using (var writer = new StreamWriter(memory))
using (var csv = new CsvWriter(writer, CultureInfo.GetCultureInfo("en")))
{
    csv.Context.RegisterClassMap<BarMap>();
    // Flatten nested collections into one list
    var bars = foos
        // Would be less typing probably if using AutoMapper to create new instances.
        .SelectMany(foo => foo.Bars.Select(bar => new Bar { BarID = $"{foo.FooID}{bar.BarID}", BarProperty1 = bar.BarProperty1, BarProperty2 = bar.BarProperty2, BarProperty3 = bar.BarProperty3 }));
    csv.WriteRecords(bars);

    writer.Flush();
    memory.Position = 0;

    using (var reader = new StreamReader(memory))
    {
        content = reader.ReadToEnd();
    }
}

CodePudding user response:

You only need the writer object and for-loop nested.

public static void Main()
        {
            // set up
            var bars1 = new List<Bar>();
            bars1.Add(new Bar() { BarID = 1, BarProperty1 = "Red", BarProperty2 = "Green", BarProperty3 = "Green" });
            bars1.Add(new Bar() { BarID = 2, BarProperty1 = "White", BarProperty2 = "Green", BarProperty3 = "Black" });
            var bars2 = new List<Bar>();
            bars2.Add(new Bar() { BarID = 1, BarProperty1 = "Pink", BarProperty2 = "Green", BarProperty3 = "Green" });
            bars2.Add(new Bar() {  BarID = 2, BarProperty1 = "White", BarProperty2 = "Green", BarProperty3 = "Black" });
            bars2.Add(new Bar() {  BarID = 2, BarProperty1 = "Cyan", BarProperty2 = "Green", BarProperty3 = "Black" });

            var foo1 = new Foo() { FooID = 1, Bars = bars1 };
            var foo2 = new Foo() { FooID = 2, Bars = bars2 };
            var foos = new List<Foo>() { foo1, foo2 };

            // write CSV
            using (var writer = new StreamWriter("file.csv"))
            using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                writer.WriteLine("Id,Prop1,Prop2,Prop3");
                foreach (var foo in foos)
                {
                    
                    foreach (var bar in foo.Bars)
                    {
                        writer.Write(foo.FooID);
                        csv.WriteRecord(bar);
                        csv.NextRecord();
                    }
                    
                }
            }
        }
  • Related