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.
Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList);
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With