Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

c#-2.0

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.

like image 871
Nano HE Avatar asked Dec 13 '10 07:12

Nano HE


People also ask

How do I convert a list of strings to a list of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList);

How do I save a list as a string?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.


1 Answers

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();
    
like image 93
Jon Skeet Avatar answered Sep 21 '22 14:09

Jon Skeet