I have searched this online, but I can\'t find the answer I am looking for.
Basically I have the following enum:
public enum typFoo : int
{
itemA
You can enumerate over the enum descriptors:
Dictionary<int, string> enumDictionary = new Dictionary<int, string>();
foreach(var name in Enum.GetNames(typeof(typFoo))
{
enumDictionary.Add((int)((typFoo)Enum.Parse(typeof(typFoo)), name), name);
}
That should put the value of each item and the name into your dictionary.
Adapting Ani's answer so that it can be used as a generic method (thanks, toddmo):
public static Dictionary<int, string> EnumDictionary<T>()
{
if (!typeof(T).IsEnum)
throw new ArgumentException("Type must be an enum");
return Enum.GetValues(typeof(T))
.Cast<T>()
.ToDictionary(t => (int)(object)t, t => t.ToString());
}
Using reflection:
Dictionary<int,string> mydic = new Dictionary<int,string>();
foreach (FieldInfo fi in typeof(typFoo).GetFields(BindingFlags.Public | BindingFlags.Static))
{
mydic.Add(fi.GetRawConstantValue(), fi.Name);
}
Another extension method that builds on Arithmomaniac's example:
/// <summary>
/// Returns a Dictionary<int, string> of the parent enumeration. Note that the extension method must
/// be called with one of the enumeration values, it does not matter which one is used.
/// Sample call: var myDictionary = StringComparison.Ordinal.ToDictionary().
/// </summary>
/// <param name="enumValue">An enumeration value (e.g. StringComparison.Ordianal).</param>
/// <returns>Dictionary with Key = enumeration numbers and Value = associated text.</returns>
public static Dictionary<int, string> ToDictionary(this Enum enumValue)
{
var enumType = enumValue.GetType();
return Enum.GetValues(enumType)
.Cast<Enum>()
.ToDictionary(t => (int)(object)t, t => t.ToString());
}
ArgumentException
if the type is not System.Enum
, thanks to Enum.GetValues
enum
constraint is available yet)public static Dictionary<T, string> ToDictionary<T>() where T : struct
=> Enum.GetValues(typeof(T)).Cast<T>().ToDictionary(e => e, e => e.ToString());
See: How do I enumerate an enum in C#?
foreach( typFoo foo in Enum.GetValues(typeof(typFoo)) )
{
mydic.Add((int)foo, foo.ToString());
}