首页 文章

如何将枚举转换为C#中的列表? [重复]

提问于
浏览
512

这个问题在这里已有答案:

有没有办法将 enum 转换为包含所有枚举选项的列表?

14 回答

  • 65

    这将返回Enum的所有值的 IEnumerable<SomeEnum> .

    Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>();
    

    如果你想要它是 List<SomeEnum> ,只需在 .Cast<SomeEnum>() 之后添加 .ToList() .

    要在Array上使用Cast函数,您需要在using部分中使用 System.Linq .

  • 1

    更简单的方法:

    Enum.GetValues(typeof(SomeEnum))
        .Cast<SomeEnum>()
        .Select(v => v.ToString())
        .ToList();
    
  • 24

    简短的回答是,使用:

    (SomeEnum[])Enum.GetValues(typeof(SomeEnum))
    

    如果你需要一个局部变量,那就是 var allSomeEnumValues = (SomeEnum[])Enum.GetValues(typeof(SomeEnum)); .

    Why is the syntax like this?!

    static 方法GetValues是在旧的.NET 1.0天中引入的 . 它返回运行时类型为 SomeEnum[] 的一维数组 . 但是因为它's a non-generic method (generics was not introduced until .NET 2.0), it can't声明它的返回类型(编译时返回类型) .

    .NET数组确实有一种协方差,但因为 SomeEnum 将是 value type ,并且因为数组类型协方差不适用于值类型,所以它们甚至不能将返回类型声明为 object[]Enum[] . (这与例如具有编译时返回类型 object[]this overload of GetCustomAttributes from .NET 1.0不同,但实际上返回 SomeAttribute[] 类型的数组,其中 SomeAttribute 必然是引用类型 . )

    因此,.NET 1.0方法必须将其返回类型声明为 System.Array . 但我保证你是 SomeEnum[] .

    每次使用相同的枚举类型再次调用 GetValues 时,都必须分配一个新数组并将值复制到新数组中 . 那个's because arrays might be written to (modified) by the 667814 of the method, so they have to make a new array to be sure the values are unchanged. .NET 1.0 didn'有很好的只读集合 .

    如果您需要许多不同位置的所有值的列表,请考虑只调用一次 GetValues 并将结果缓存在只读包装器中,例如:

    public static readonly ReadOnlyCollection<SomeEnum> AllSomeEnumValues
        = Array.AsReadOnly((SomeEnum[])Enum.GetValues(typeof(SomeEnum)));
    

    然后您可以多次使用 AllSomeEnumValues ,并且可以安全地重复使用相同的集合 .

    Why is it bad to use .Cast<SomeEnum>()?

    许多其他答案使用 .Cast<SomeEnum>() . 这个问题是它使用了 Array 类的非泛型 IEnumerable 实现 . 这应该包括将每个值装入 System.Object 框,然后使用 Cast<> 方法再次打开所有这些值 . 幸运的是 .Cast<> 方法似乎在开始迭代集合之前检查其 IEnumerable 参数( this 参数)的运行时类型,所以它毕竟不是那么糟糕 . 事实证明 .Cast<> 允许相同的数组实例通过 .

    如果您按照 .ToArray().ToList() 进行操作,如下所示:

    Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>().ToList() // DON'T do this
    

    你有另一个问题:当你调用 GetValues 然后用 .ToList() 调用创建一个新的集合( List<> )时,你创建一个新的集合(数组) . 这是整个集合的一个(额外)冗余分配来保存值 .

  • 1

    这是我喜欢的方式,使用LINQ:

    public class EnumModel
    {
        public int Value { get; set; }
        public string Name { get; set; }
    }
    
    public enum MyEnum
    {
        Name1=1,
        Name2=2,
        Name3=3
    }
    
    public class Test
    {
        List<EnumModel> enums = ((MyEnum[])Enum.GetValues(typeof(MyEnum))).Select(c => new EnumModel() { Value = (int)c, Name = c.ToString() }).ToList();
    }
    

    希望能帮助到你

  • 1
    List <SomeEnum> theList = Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>().ToList();
    
  • 0

    非常简单的答案

    这是我在我的一个应用程序中使用的属性

    public List<string> OperationModes
    {
        get
        {
           return Enum.GetNames(typeof(SomeENUM)).ToList();
        }
    }
    
  • 83

    我总是习惯得到像这样的 enum 值列表:

    Array list = Enum.GetValues(typeof (SomeEnum));
    
  • 866

    这里有用...用于将值放入列表的一些代码,它将枚举转换为文本的可读形式

    public class KeyValuePair
      {
        public string Key { get; set; }
    
        public string Name { get; set; }
    
        public int Value { get; set; }
    
        public static List<KeyValuePair> ListFrom<T>()
        {
          var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>());
          return array
            .Select(a => new KeyValuePair
              {
                Key = a.ToString(),
                Name = a.ToString().SplitCapitalizedWords(),
                Value = Convert.ToInt32(a)
              })
              .OrderBy(kvp => kvp.Name)
             .ToList();
        }
      }
    

    ..和支持System.String扩展方法:

    /// <summary>
    /// Split a string on each occurrence of a capital (assumed to be a word)
    /// e.g. MyBigToe returns "My Big Toe"
    /// </summary>
    public static string SplitCapitalizedWords(this string source)
    {
      if (String.IsNullOrEmpty(source)) return String.Empty;
      var newText = new StringBuilder(source.Length * 2);
      newText.Append(source[0]);
      for (int i = 1; i < source.Length; i++)
      {
        if (char.IsUpper(source[i]))
          newText.Append(' ');
        newText.Append(source[i]);
      }
      return newText.ToString();
    }
    
  • 10
    Language[] result = (Language[])Enum.GetValues(typeof(Language))
    
  • 3
    public class NameValue
    {
        public string Name { get; set; }
        public object Value { get; set; }
    }
    
    public class NameValue
    {
        public string Name { get; set; }
        public object Value { get; set; }
    }
    
    public static List<NameValue> EnumToList<T>()
    {
        var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>()); 
        var array2 = Enum.GetNames(typeof(T)).ToArray<string>(); 
        List<NameValue> lst = null;
        for (int i = 0; i < array.Length; i++)
        {
            if (lst == null)
                lst = new List<NameValue>();
            string name = array2[i];
            T value = array[i];
            lst.Add(new NameValue { Name = name, Value = value });
        }
        return lst;
    }
    

    将枚举转换为列表更多信息here .

  • 5
    /// <summary>
    /// Method return a read-only collection of the names of the constants in specified enum
    /// </summary>
    /// <returns></returns>
    public static ReadOnlyCollection<string> GetNames()
    {
        return Enum.GetNames(typeof(T)).Cast<string>().ToList().AsReadOnly();   
    }
    

    其中 T 是一种枚举;添加这个:

    using System.Collections.ObjectModel;
    
  • 20

    如果你想将Enum int作为键并将name命名为value,那么如果你将数字存储到数据库并且它来自Enum,那就太好了!

    void Main()
    {
         ICollection<EnumValueDto> list = EnumValueDto.ConvertEnumToList<SearchDataType>();
    
         foreach (var element in list)
         {
            Console.WriteLine(string.Format("Key: {0}; Value: {1}", element.Key, element.Value));
         }
    
         /* OUTPUT:
            Key: 1; Value: Boolean
            Key: 2; Value: DateTime
            Key: 3; Value: Numeric         
         */
    }
    
    public class EnumValueDto
    {
        public int Key { get; set; }
    
        public string Value { get; set; }
    
        public static ICollection<EnumValueDto> ConvertEnumToList<T>() where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
            {
                throw new Exception("Type given T must be an Enum");
            }
    
            var result = Enum.GetValues(typeof(T))
                             .Cast<T>()
                             .Select(x =>  new EnumValueDto { Key = Convert.ToInt32(x), 
                                           Value = x.ToString(new CultureInfo("en")) })
                             .ToList()
                             .AsReadOnly();
    
            return result;
        }
    }
    
    public enum SearchDataType
    {
        Boolean = 1,
        DateTime,
        Numeric
    }
    
  • 4
    private List<SimpleLogType> GetLogType()
    {
      List<SimpleLogType> logList = new List<SimpleLogType>();
      SimpleLogType internalLogType;
      foreach (var logtype in Enum.GetValues(typeof(Log)))
      {
        internalLogType = new SimpleLogType();
        internalLogType.Id = (int) (Log) Enum.Parse(typeof (Log), logtype.ToString(), true);
        internalLogType.Name = (Log)Enum.Parse(typeof(Log), logtype.ToString(), true);
        logList.Add(internalLogType);
      }
      return logList;
    }
    

    在顶部Code中,Log是Enum,SimpleLogType是日志的结构 .

    public enum Log
    {
      None = 0,
      Info = 1,
      Warning = 8,
      Error = 3
    }
    
  • 5

    您可以使用以下通用方法:

    public static List<T> GetItemsList<T>(this int enums) where T : struct, IConvertible
    {
        if (!typeof (T).IsEnum)
        {
            throw new Exception("Type given must be an Enum");
        }
    
        return (from int item in Enum.GetValues(typeof (T))
                where (enums & item) == item
                select (T) Enum.Parse(typeof (T), item.ToString(new CultureInfo("en")))).ToList();
    }
    

相关问题