Comma separated string to generic enum Array

100 Views Asked by At

I'm searching for some way to implement some TypeConverter in order to convert a comma separated string to some generic array of enum values.

var input = "Value01, Value02";
var output = new CustomEnum[] { CustomEnum.Value01, CustomEnum.Value02 };

I'm using

class StringToEnumList : ITypeConverter<string, Enum[]> ...
cfg.CreateMap<string, Enum[]>().ConvertUsing<StringToEnumList>(); ...

But this option only convert explicit Enum property types not any custom Enum property.


enum CustomEnum { Value01, Value02 }
class MyClassSource {
  public string OkProperty {get; set; }
  public string FailingProperty {get; set; }
}

class MyClassTarget {
  public Enum[] OkProperty {get; set; }
  public CustomEnum[] FailingProperty {get; set; }
}

Is there some strategy in order to implement some generic type converter from string to any custom enum avoiding the explicit registration for each custom enum ? maybe some factory or something in order to create the generic converter inspecting the property target type?

1

There are 1 best solutions below

3
Qiang Fu On

You could try following in a console app:

    public enum CustomEnum
    {
        abc,
        xyz
    }

    public class Source
    {
        public string Value1 { get; set; }
    }

    public class Destination
    {
        public CustomEnum[] Value1 { get; set; }
    }

StringToEnumList.cs

    public class StringToEnumList<T> : ITypeConverter<string, T[]>  where T : struct, Enum
    {
        public T[] Convert(string source, T[] destination, ResolutionContext context)
        {

            List<string> ls = source.Split(',').ToList();

            T[] result = new T[ls.Count];
            for (int i = 0; i < ls.Count; i++)
            {
                result[i]= Enum.Parse<T>(ls[i]);
            }
            return result;
        }
    }

program.cs

        var configuration = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<string, CustomEnum[]>().ConvertUsing(new StringToEnumList<CustomEnum>());
            cfg.CreateMap<Source, Destination>();
        });

        var mapper = new Mapper(configuration);

        var source = new Source
        {
            Value1 = "abc,xyz"
        };
        Destination result = mapper.Map<Source, Destination>(source);
        Console.ReadLine();

Test result enter image description here

(Note that this converter only work for CustomEnum. For pure Enum ("OkProperty"),you could use your converter.)