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
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>();
Enum.GetValues(typeof(Enumnum));
returns an array of the values in the 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.
Try this code:
Enum.GetNames(typeof(Enumnum));
This return a string[]
with all the enum names of the chosen enum.
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();