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

前端 未结 10 2092
刺人心
刺人心 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:21

    The OP asked for How to get an array of all enum values in C# ?

    What if you want to get an array of selected enum values in C# ?

    Your Enum

        enum WeekDays 
        {
            Sunday, 
            Monday,
            Tuesday
        }
    

    If you want to just select Sunday from your Enum.

      WeekDays[] weekDaysArray1 = new WeekDays[] { WeekDays.Sunday };
    
      WeekDays[] weekDaysArray2 = Enum.GetValues(typeof(WeekDays)).Cast<WeekDays>().Where
      (x => x == WeekDays.Sunday).ToArray();
    

    Credits goes to knowledgeable tl.

    References:

    1.

    2.

    Hope helps someone.

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

    You can use

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

    This returns an array!

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

    Something little different:

    typeof(SomeEnum).GetEnumValues();
    
    0 讨论(0)
  • 2020-12-05 02:24

    You may want to do like this:

    public enum Enumnum { 
                TypeA = 11,
                TypeB = 22,
                TypeC = 33,
                TypeD = 44
            }
    

    All int values of this enum is 11,22,33,44.

    You can get these values by this:

    var enumsValues = Enum.GetValues(typeof(Enumnum)).Cast<Enumnum>().ToList().Select(e => (int)e);
    

    string.Join(",", enumsValues) is 11,22,33,44.

    0 讨论(0)
提交回复
热议问题