Using csvHelper to read cell content into List or Array

PHOTO EMBED

Wed Apr 01 2020 08:42:17 GMT+0000 (Coordinated Universal Time)

Saved by @Anier #C#

The TypeConverter class is under namespace CsvHelper.TypeConversion

The TypeConverterAttribute is under namespace CsvHelper.Configuration.Attributes

    public class ToIntArrayConverter : TypeConverter
    {
        public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
        {
            string[] allElements = text.Split(',');
            int[] elementsAsInteger = allElements.Select(s => int.Parse(s)).ToArray();
            return new List<int>(elementsAsInteger);
        }

        public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
        {
            return string.Join(',', ((List<int>)value).ToArray());
        }
    }
To use this converter, simply add the following TypeConverterAttribute annotations on top of your properties:
To use this converter, simply add the following TypeConverterAttribute annotations on top of your properties:

    public class Names
    {
        [Name("name")]
        public string Name { get; set; }

        [Name("numbersA")]
        [TypeConverter(typeof(ToIntArrayConverter))]
        public List<int> NumbersA { get; set; }

        [Name("numbersB")]
        [TypeConverter(typeof(ToIntArrayConverter))]
        public List<int> NumbersB { get; set; }
    }
content_copyCOPY

You can implement a custom type converter and use it during conversion (both directions) for your two properties.

https://stackoverflow.com/questions/60966194/using-csvhelper-to-read-cell-content-into-list-or-array