How to use EnumConverter with CsvHelper

后端 未结 4 1355
执念已碎
执念已碎 2020-12-10 18:08

I\'m using CsvHelper to serialize a class to csv file - until here everything works well.

Now I\'m trying to find a way to convert the class\'s enum properties to th

相关标签:
4条回答
  • 2020-12-10 18:42

    I used Yarimi's solution, but found it can't read the enum value back from the .csv (can write ok)

    my solution is to make the class extend from EnumTypeConverter, not DefaultTypeConverter.

    here is the full code

        public class OurEnumConverter<T> : CsvHelper.TypeConversion.EnumConverter where T : struct
        {
    
            public OurEnumConverter(): base(typeof(T))
            { }
    
            public override string ConvertToString(CsvHelper.TypeConversion.TypeConverterOptions options, object value)
            {
                T result;
                if (Enum.TryParse<T>(value.ToString(), out result))
                {
                    return (Convert.ToInt32(result)).ToString();
                }
                return base.ConvertToString(options, value);
                //throw new InvalidCastException(String.Format("Invalid value to EnumConverter. Type: {0} Value: {1}", typeof (T), value));
            }
            public override object ConvertFromString(TypeConverterOptions options, string text)
            {
                int parsedValue;
                //System.Diagnostics.Debug.WriteLine($"{typeof(T).Name} = {text}");
                if (Int32.TryParse(text, out parsedValue))
                {
                    return (T)(object)parsedValue;
                }
                return base.ConvertFromString(options, text);
                //throw new InvalidCastException(String.Format("Invalid value to EnumConverter. Type: {0} Value: {1}", typeof(T), text));
            }
    
        }
    

    and here is how it's used

    public class TickTradeClassMap : CsvHelper.Configuration.CsvClassMap<TickData.TickTrade>
        {
            public TickTradeClassMap()
            {
                Map(m => m.price);
                Map(m => m.size);
                Map(m => m.exchange).TypeConverter<OurEnumConverter<ATExchangeEnum>>();
                Map(m => m.condition1).TypeConverter<OurEnumConverter<ATTradeConditionEnum>>();
            }
        }
    
    0 讨论(0)
  • 2020-12-10 18:55

    This is how I did it for the latest version of CSV Helper which is 7.1.1:

    public class AggregateEnumConverter<T> : EnumConverter where T : struct
    {
        public AggregateEnumConverter() : base(typeof(T)) { }
    
        public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
        {
            if(!Enum.TryParse(text, out AggregateType aggregateType))
            {
                // This is just to make the user life simpler...
                if(text == "24HAVG")
                {
                    return AggregateType._24HAVG;
                }
    
                // If an invalid value is found in the CSV for the Aggregate column, throw an exception...
                throw new InvalidCastException($"Invalid value to EnumConverter. Type: {typeof(T)} Value: {text}");
            }
    
            return aggregateType;
        }
    }
    

    Note: the code above is making use of C# 7 new inline out variables.
    More info here: How should I convert a string to an enum in C#?

    This is how you make use of the custom EnumConverter:

    /// <summary>
    /// Maps Tag class properties to the CSV columns' names
    /// </summary>
    public sealed class TagMap : ClassMap<Tag>
    {
        public TagMap(ILogger<CsvImporter> logger)
        {
            Map(tag => tag.Aggregate).Name("aggregate").TypeConverter<AggregateEnumConverter<AggregateType>>();
        }
    }
    
    0 讨论(0)
  • 2020-12-10 18:58

    This is the solution I made:

    public class CalendarExceptionEnumConverter<T> : DefaultTypeConverter  where T : struct
        {
            public override string ConvertToString(TypeConverterOptions options, object value)
            {
                T result;
                if(Enum.TryParse<T>(value.ToString(),out result))
                {
                    return (Convert.ToInt32(result)).ToString();
                }
    
                throw new InvalidCastException(String.Format("Invalid value to EnumConverter. Type: {0} Value: {1}",typeof(T),value));
            }
        }
    

    and used it as the following:

    Map(m => m.ExceptionEntityType).TypeConverter<CalendarExceptionEnumConverter<CalendarExceptionEntityType>>();
    
    0 讨论(0)
  • 2020-12-10 19:09

    Add a int property to your TradingCalendarException class that casts back and forth to your custom enum, CalendarExceptionEntityType, like:

    public int ExceptionEntityTypeInt { 
        get { return (int)ExceptionEntityType; } 
        set { ExceptionEntityType = (CalendarExceptionEntityType)value; } 
    }
    

    Use Map(m => m.ExceptionEntityTypeInt).Index(0).Name("EXCEPTION_ENTITY_TYPE_INT") instead of your enum converter Map(m => m.ExceptionEntityType).Index(0).Name("EXCEPTION_ENTITY_TYPE").TypeConverter(new MyMapping())

    0 讨论(0)
提交回复
热议问题