Export nested collection with FileHelpers

1.4k Views Asked by At
[DelimitedRecord(",")]
public class SampleType
{
    public string Field1;
    public int Field2;

    public IEnumerable<ChildClass>  Collection { get; set; }
}

[DelimitedRecord("|")]
public class ChildClass
{
     public string Value { get; set; }
}

I would like to convert a list of SampleTypes to CSV format using FileHelpers. How do I get it to output the inner 'Collection' within each instance of SampleType?

So a row output would look something like this...

"Field1Value", "7", "Value1|Value2|Value3"

1

There are 1 best solutions below

2
On BEST ANSWER

Define a new read-only property in your class like this:

[DelimitedRecord(",")]
public class SampleType
{
    public string Field1;
    public int Field2;

    public IEnumerable<ChildClass>  Collection { get; set; }
    public string CollectionValues
    {
       get
       {
          string.Join("|", this.Collection.Select(c => c.Value));
       }
    }
}

I have never used FileHelper, but I assume you should be able to export a CSV file containing Field1, Field2, and CollectionValues.

UPDATE:

Looking at FileHelpers' documentation, it seems like FileHelpers' solution for this situation is using a Custom FieldConverter. You can define a custom converter like this:

public class MyCustomConverter : ConverterBase 
{ 
    public override object StringToField(string from) 
    { 
        return from.Split('|').Select(s => new ChildClass { Value = s }); 
    } 


    public override string FieldToString(object fieldValue) 
    { 
        IEnumerable<ChildClass> collection = (IEnumerable<ChildClass>)fieldValue;

        return string.Join("|", collection.Select(c => c.Value));
    }          
} 

Then, you can use it in your class like this:

[DelimitedRecord(",")]
public class SampleType
{
    public string Field1;
    public int Field2;

    [FieldConverter(typeof(MyCustomConverter))]
    public IEnumerable<ChildClass>  Collection { get; set; }
}