Csvhelper: Writing a collection that contains collections

Created on 15 May 2015  路  4Comments  路  Source: JoshClose/CsvHelper

Hi, is it possible to write a collection that contains collections, e.g. parent record, and child records?

--> Parent1, Name, Age
-->--> Child1, Field1, Field2
-->--> Child2, Field1, Field2
--> Parent2, Name, Age
-->--> Child3, Field1, Field2
...

I thought that the AutoMapper might do this via it's recursion, however when I tried it using WriteRecords(items) however only the parent record was written.

Thanks

All 4 comments

You cannot have nested collections as far as I know. You CAN have nested objects however. See reference maps just under the AutoMapping section @ http://joshclose.github.io/CsvHelper/

Enumerable properties are supported in version 3.0.

Can you provide example to add row for each nested object ? (I'm ok to use version 3.0 but how ?)

void Main()
{
    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream))
    using (var reader = new StreamReader(stream))
    using (var csv = new CsvReader(reader))
    {
        writer.WriteLine("Id,Name,A,B,C");
        writer.WriteLine("1,one,a,b,c");
        writer.WriteLine("2,two,d,e,c");
        writer.Flush();
        stream.Position = 0;

        csv.Configuration.RegisterClassMap<TestMap>();
        csv.GetRecords<Test>().ToList().Dump();
    }
}

public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<string> ExtraStrings { get; set; }
}

public sealed class TestMap : CsvClassMap<Test>
{
    public TestMap()
    {
        Map( m => m.Id );
        Map( m => m.Name );
        Map( m => m.ExtraStrings ).Index( 2 );
    }
}

You can also take a look at the unit tests if you like. https://github.com/JoshClose/CsvHelper/tree/master/src/CsvHelper.Tests/TypeConversion

Was this page helpful?
0 / 5 - 0 ratings