Introduction
This helper was written to supply the enum over an Web Api call to list the enum/flags values and display strings, that will still match the code's ordinal value. It was then later used to collect data and seed enum's into the databse.
By setting the DisplayAttribute on the enum and setting the Description property, this helper will assist with getting the "displaystring". This is very handy if you want to use human readable text instead of the ordinal's key.
Used in DbEnum & IDbEnum: https://www.codeproject.com/Reference/1186336/DbEnum
public static class EnumHelper
{
public static IEnumerable<dynamic> GetStruct<TEnum>() where TEnum : struct
{
return (from v in GetPrivateDisplayList<TEnum>()
select new { Id = v, Description = v.ToString() });
}
public static IEnumerable<dynamic> GetDisplayList<TEnum>() where TEnum : struct
{
return (from v in GetPrivateDisplayList<TEnum>()
select new { Id = v, Description = v.GetDisplayString() });
}
public static string GetDisplayString(this Enum source)
{
var da = source.GetDisplayAttribute();
return da != null ? da.Description : source.ToString();
}
private static IEnumerable<Enum> GetPrivateDisplayList<TEnum>() where TEnum : struct
{
var ti = typeof(TEnum).GetTypeInfo();
if (!ti.IsEnum) return null;
return ti.GetEnumValues().Cast<Enum>();
}
private static DisplayAttribute GetDisplayAttribute(this Enum source)
{
var fi = source.GetType().GetTypeInfo().GetField(source.ToString());
return fi.GetCustomAttribute<DisplayAttribute>();
}
}