Search code examples
c#csvcsvhelper

Writing enumerable to csv file


I'm sure its very straightforward but I am struggling to figure out how to write an array to file using CSVHelper.

I have a class for example

public class Test
{
public Test()
{
data = new float[]{0,1,2,3,4};
}
 public float[] data{get;set;}
}

i would like the data to be written with each array value in a separate cell. I have a custom converter below which is instead providing one cell with all the values in it.

What am I doing wrong?

public class DataArrayConverter<T> : ITypeConverter
{
    public string ConvertToString(TypeConverterOptions options, object value)
    {
        var data = (T[])value;

       var s = string.Join(",", data);

    }

    public object ConvertFromString(TypeConverterOptions options, string text)
    {
        throw new NotImplementedException();
    }

    public bool CanConvertFrom(Type type)
    {
        return type == typeof(string);
    }

    public bool CanConvertTo(Type type)
    {
        return type == typeof(string);
    }
}

Solution

  • Unfortunately, it doesn't work like that. Since you are returning , in the converter, it will quote the field, as that is a part of a single field.

    Currently the only way to accomplish what you want is to write manually, which isn't too horrible.

    foreach( var test in list )
    {
        foreach( var item in test.Data )
        {
            csvWriter.WriteField( item );
        }
    
        csvWriter.NextRecord();
    }
    

    Update

    Version 3 has support for reading and writing IEnumerable properties.