c# - 如何将 List<string> 转换为 List<myEnumType>?

标签 c# c#-2.0

我未能转换 List<string>List<myEnumType> .我不知道为什么?

string Val = it.Current.Value.ToString(); // works well here
List<myEnumType> ValList = new List<myEnumType>(Val.Split(',')); // compile failed

原因myEnumType类型定义为字符串枚举类型,

public enum myEnumType
{
    strVal_1,
    strVal_2,
    strVal_3,
}

有什么问题吗?感谢您的回复。

最佳答案

编辑:糟糕,我也错过了 C# 2 标签。我将在下面保留其他可用选项,但是:

在 C# 2 中,您可能最好使用 List<T>.ConvertAll :

List<MyEnumType> enumList = stringList.ConvertAll(delegate(string x) {
    return (MyEnumType) Enum.Parse(typeof(MyEnumType), x); });

或使用 Unconstrained Melody :

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

请注意,这确实假设您确实有一个 List<string>首先,这对你的标题是正确的,但对你问题中的正文不正确。幸运的是,有一个等效的静态 Array.ConvertAll 你必须像这样使用的方法:

MyEnumType[] enumArray = Array.ConvertAll(stringArray, delegate (string x) {
    return (MyEnumType) Enum.Parse(typeof(MyEnumType), x); });

原始答案

两种选择:

  • 在 LINQ 查询中使用 Enum.Parse 和强制转换:

    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 Melody项目:

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

关于c# - 如何将 List<string> 转换为 List<myEnumType>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4426537/

相关文章:

c# - 这在 C# 中究竟意味着什么?

c# - 从 2 个网络服务制作一份复杂类型的副本

c# - 给定边界框和一条线(两点),确定线是否与框相交

c# - 线程问题

c# - 虚拟成员按运行时类型分派(dispatch)

c# - 在 select from with inner join in sql 查询中编写 linq similiar where in select from

c# - 检查日期选择器值是否小于今天的日期

c# - 针对 "%"搜索字符串

c# - 事件日志代码错误无法找到事件源?