Let's say I have the following enum
:
public enum Colors
{
White = 10,
Black = 20,
Red = 30,
Blue = 40
}
I'm wondering if there is a way to iterate through all the members of Colors
to find the member names and their values.
You can use Enum.GetNames and Enum.GetValues:
var names = Enum.GetNames(typeof(Colors));
var values = Enum.GetValues(typeof(Colors));
for (int i=0;i<names.Length;++i)
{
Console.WriteLine("{0} : {1}", names[i], (int)values.GetValue(i));
}
Note: When I tried to run the code using values[i]
, it threw an exception because values
is of type Array
.
You could do something like this
for (int i = 0; i < typeof(DepartmentEnum).GetFields().Length - 1; i++)
{
DepartmentEnum de = EnumExtensions.NumberToEnum<DepartmentEnum>(i);
pairs.Add(new KeyValuePair<string, string>(de.ToDescription(), de.ToString()));
}
Here is the extension itself:
public static class EnumExtensions
{
public static string ToDescription(this Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),false);
if (attrs != null && attrs.Length > 0)
return ((DescriptionAttribute)attrs[0]).Description;
}
return en.ToString();
}
public static TEnum NumberToEnum<TEnum>(int number )
{
return (TEnum)Enum.ToObject(typeof(TEnum), number);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With