Jan
Jan

Reputation: 317

Convert List<object> to List<MyEnumType> with MyEnumType in Type variable

I want to convert a List<string> to List<MyEnum>.

The problem is, if I parse all items of List<string> to MyEnum, the new list will stay as List<object>.

static void ConvertList(List<string> stringList, Type enumType)
{
    var enumList = stringList.Select(a => Enum.Parse(enumType, a)).ToList();

    Console.WriteLine("Original Type: " + typeof(List<MyEnum>));
    Console.WriteLine("EnumList Type: " + enumList.GetType());
    Console.WriteLine("EnumList First Element Type: " + enumList.First().GetType());
    Console.Read();
}

// Console.Out
// Original Type: System.Collections.Generic.List`1[ConsoleApplication1.MyEnum]
// EnumList Type: System.Collections.Generic.List`1[System.Object]
// EnumList First Element Type: ConsoleApplication1.MyEnum

Is it possible to convert the list to List<MyEnum> just by a Type variable?

Thanks in advance!

Edit:

Thanks for your help.

But I need to clarify that the enum type is ONLY stored in an instance of Type. Thanks!

I can't call something like ConvertList<MyEnum>.

Upvotes: 0

Views: 87

Answers (2)

Hossain Muctadir
Hossain Muctadir

Reputation: 3626

You can try something like this,

static void ConvertList<T>(List<string> stringList)
{
    var enumList = stringList.Select(a => (T)Enum.Parse(typeof(T), a)).ToList();
}

And call the method,

 ConvertList<MyEnum>(new List<string> { "Value1", "Value2" });

Update

Changing the calling mechanism can help in this case,

MethodInfo method = typeof(Program).GetMethod("ConvertList", BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
var type = typeof (MyEnum);
MethodInfo generic = method.MakeGenericMethod(type);
generic.Invoke(null, new[] {new List<string> {"Value1", "Value2"}});

Upvotes: 3

Georg
Georg

Reputation: 5771

The answer is reflection, but it's ugly.

    static object ConvertList<T>(List<string> stringList)
    {
        return stringList.Select(a => (T)Enum.Parse(typeof(T), a)).ToList();
    }

    static object ConvertList(List<string> stringList, Type enumType)
    {
        var method = new Func<List<string>, object>(ConvertList<object>).Method.GetGenericMethodDefinition();
        return method.MakeGenericMethod(enumType).Invoke(null, new object[] { stringList });
    }

Upvotes: 1

Related Questions