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();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…