如何在 C # 中获得一个包含所有枚举值的数组?

我有一个枚举,我想显示所有可能的值。是否有一种方法可以获得枚举的所有可能值的数组或列表,而不是手动创建这样的列表?例如:。如果我有枚举:

public enum Enumnum { TypeA, TypeB, TypeC, TypeD }

我怎样才能得到一个包含 { TypeA, TypeB, TypeC, TypeD }List<Enumnum>

114125 次浏览

You can use

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

This returns an array!

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();
Enum.GetValues(typeof(Enumnum));

returns an array of the values in the Enum.

Try this code:

Enum.GetNames(typeof(Enumnum));

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

with this:

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

and you can access values array like so:

Array myArray = Enum.GetValues(typeof(Enumnum));

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.

Something little different:

typeof(SomeEnum).GetEnumValues();

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.

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

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.

This is way easier now with the generic method in .NET 5.0.

ColorEnum[] colors = Enum.GetValues<ColorEnum>();

MS Doc: Enum.GetValues