How to get an array of all enum values in C#?

前端 未结 10 2091
刺人心
刺人心 2020-12-05 01:48

I have an enum that I\'d like to display all possible values of. Is there a way to get an array or list of all the possible values of the enum instead of manually creating s

相关标签:
10条回答
  • 2020-12-05 02:00

    If you prefer a more generic way, here it is. You can add up more converters as per your need.

        public static class EnumConverter
        {
    
            public static string[] ToNameArray<T>()
            {
                return Enum.GetNames(typeof(T)).ToArray();
            }
    
            public static Array ToValueArray<T>()
            {
                return Enum.GetValues(typeof(T));
            }
    
            public static List<T> ToListOfValues<T>()
            {
                return Enum.GetValues(typeof(T)).Cast<T>().ToList();
            }
    
    
            public static IEnumerable<T> ToEnumerable<T>()
            {
                return (T[])Enum.GetValues(typeof(T));
            }
    
        }
    

    Sample Implementations :

       string[] roles = EnumConverter.ToStringArray<ePermittedRoles>();
       List<ePermittedRoles> roles2 = EnumConverter.ToListOfValues<ePermittedRoles>();
       Array data = EnumConverter.ToValueArray<ePermittedRoles>();
    
    0 讨论(0)
  • 2020-12-05 02:05
    Enum.GetValues(typeof(Enumnum));
    

    returns an array of the values in the Enum.

    0 讨论(0)
  • 2020-12-05 02:06

    with this:

    string[] myArray = Enum.GetNames(typeof(Enumnum));

    and you can access values array like so:

    Array myArray = Enum.GetValues(typeof(Enumnum));
    0 讨论(0)
  • 2020-12-05 02:06

    also you can use

    var enumAsJson=typeof(SomeEnum).Name + ":[" + string.Join(",", Enum.GetValues(typeof(SomeEnum)).Cast<SomeEnum>().Select(e => e.ToString())) + "]";
    

    for get all elements in enum as json format.

    0 讨论(0)
  • 2020-12-05 02:11

    Try this code:

    Enum.GetNames(typeof(Enumnum));
    

    This return a string[] with all the enum names of the chosen enum.

    0 讨论(0)
  • 2020-12-05 02:14

    This gets you a plain array of the enum values using Enum.GetValues:

    var valuesAsArray = Enum.GetValues(typeof(Enumnum));
    

    And this gets you a generic list:

    var valuesAsList = Enum.GetValues(typeof(Enumnum)).Cast<Enumnum>().ToList();
    
    0 讨论(0)
提交回复
热议问题