Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

c# - How can I convert List<string> to List<myEnumType>?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...