我怎么能转换列表<串GT;列出< myEnumType&GT ;? [英] How can I convert List<string> to List<myEnumType>?

查看:95
本文介绍了我怎么能转换列表<串GT;列出< myEnumType&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没能列表与LT转换;串> 列表< 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



引起 myEnumType 键入定义为字符串枚举类型,因为这,

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.

推荐答案

编辑:哎呀,我错过了C#2标签为好。我会留下可用的其他选项下面,但是:

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

在C#2,你可能最好使用的 列表< T> .ConvertAll

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

无约束旋律

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

请注意,这并假设你真的有一个列表<串> 下手,这是正确的为您的标题,但不是在你的问题中的身体。幸运的是有一个等效静 Array.ConvertAll 你不得不使用这样的方法:

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






原来的答复

有两种选择:


  • 使用Enum.Parse并在投LINQ查询:

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

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


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




  • 使用我的Unconstrained旋律项目:

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


  • 这篇关于我怎么能转换列表&LT;串GT;列出&LT; myEnumType&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆