How can I convert List<string> to List<myEnumType>?

浪尽此生 提交于 2019-12-20 09:37:04

问题


I failed to convert List<string> to List<myEnumType>. I don't know why?

string Val = it.Current.Value.ToString(); // works well here
List<myEnumType> ValList = new List<myEnumType>(Val.Split(',')); // compile failed

Of cause myEnumType type defined as string enum type as this,

public enum myEnumType
{
    strVal_1,
    strVal_2,
    strVal_3,
}

Is there anything wrong? Appreciated for you replies.


回答1:


EDIT: Oops, I missed the C# 2 tag as well. I'll leave the other options available below, but:

In C# 2, you're probably best using List<T>.ConvertAll:

List<MyEnumType> enumList = stringList.ConvertAll(delegate(string x) {
    return (MyEnumType) Enum.Parse(typeof(MyEnumType), x); });

or with Unconstrained Melody:

List<MyEnumType> enumList = stringList.ConvertAll(delegate(string x) {
    return Enums.ParseName<MyEnumType>(x); });

Note that this does assume you really have a List<string> to start with, which is correct for your title but not for the body in your question. Fortunately there's an equivalent static Array.ConvertAll method which you'd have to use like this:

MyEnumType[] enumArray = Array.ConvertAll(stringArray, delegate (string x) {
    return (MyEnumType) Enum.Parse(typeof(MyEnumType), x); });

Original answer

Two options:

  • Use Enum.Parse and a cast in a LINQ query:

    var enumList = stringList
              .Select(x => (MyEnumType) Enum.Parse(typeof(MyEnumType), x))
              .ToList();
    

or

    var enumList = stringList.Select(x => Enum.Parse(typeof(MyEnumType), x))
                             .Cast<MyEnumType>()
                             .ToList();
  • Use my Unconstrained Melody project:

    var enumList = stringList.Select(x => Enums.ParseName<MyEnumType>(x))
                             .ToList();
    



回答2:


In C# 2.0:

List<myEnumType> ValList = new List<myEnumType>();
foreach (string x in Val.Split(','))
    ValList.Add((MyEnumType) Enum.Parse(typeof(MyEnumType), x));



回答3:


        List<String> list = new List<String>();

        list.Add("strVal_1");
        list.Add("strVal_2");
        list.Add("strVal_3");

        List<myEnumType> enumList = new List<myEnumType>();

        foreach (var item in list)
        {
            enumList.Add((myEnumType)Enum.Parse(typeof(myEnumType), item));
        }



回答4:


Create an extension method and with Select do the Work:

public static class ExtensionClass
{
    public static myEnumType GetEnumValue(this string input)
    {
        if (input == myEnumType.strVal_1.ToString())
            return myEnumType.strVal_1;
        return input == myEnumType.strVal_2.ToString() ? myEnumType.strVal_2 : myEnumType.strVal_3;
    }
}

List<myEnumType> ValList = new List<myEnumType>(Val.Split(',').Select(p=>p.GetEnumValue())); 

I missed c#2.0 tag :)




回答5:


I added an extension method to IEnumerable<string> to do this for me. Skeet's answer is good, obviously, but it will throw an exception if the strings aren't valid for the enum (which you may or may not want), and it's a pretty ugly looking line.

public static class StringEnumerableExtensions {
    public static IEnumerable<T> StringsToEnums<T>( this IEnumerable<string> strs) where T : struct, IConvertible {
        Type t = typeof( T );

        var ret = new List<T>();

        if( t.IsEnum ) {
            T outStr;
            foreach( var str in strs ) {
                if( Enum.TryParse( str, out outStr ) ) {
                    ret.Add( outStr );
                }
            }
        }

        return ret;
    }
}

Given this enum:

public enum ColorEnum { Blue, Yellow }

You can use this like so:

var colors = new List<string>() {"Blue","Yellow","Black"};
var colorEnums = colors.StringsToEnums<ColorEnum>();

And you'll get a list with just Blue and Yellow.



来源:https://stackoverflow.com/questions/4426537/how-can-i-convert-liststring-to-listmyenumtype

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!