I'm looking to create a function that converts an Enum to a dictionary list. The Enum names will also be converted into a more human readable form. I'd like to just call the function, provide the enum type, and get the dictionary back. I believe I'm almost there I just can't seem to figure out how to cast the enum to the correct type. (Getting an error on the 'returnList.Add' line). Right now I'm just using var for the type, however I do know the type, as it's passed in.
internal static Dictionary<int,string> GetEnumList(Type e)
{
List<string> exclusionList =
new List<string> {"exclude"};
Dictionary<int,string> returnList = new Dictionary<int, string>();
foreach (var en in Enum.GetValues(e))
{
// split if necessary
string[] textArray = en.ToString().Split('_');
for (int i=0; i< textArray.Length; i++)
{
// if not in the exclusion list
if (!exclusionList
.Any(x => x.Equals(textArray[i],
StringComparison.OrdinalIgnoreCase)))
{
textArray[i] = Thread.CurrentThread.CurrentCulture.TextInfo
.ToTitleCase(textArray[i].ToLower());
}
}
returnList.Add((int)en, String.Join(" ", textArray));
}
return returnList;
}
You can use generic method, which will create dictionary with enum values and names:
public static Dictionary<int, string> GetEnumList<T>()
{
Type enumType = typeof(T);
if (!enumType.IsEnum)
throw new Exception("Type parameter should be of enum type");
return Enum.GetValues(enumType).Cast<int>()
.ToDictionary(v => v, v => Enum.GetName(enumType, v));
}
Feel free to modify default enum name as you need. Usage:
var daysDictionary = Extensions.GetEnumList<DayOfWeek>();
string monday = daysDictionary[1];
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