public static class EnumHelper
{
/// <summary>
/// Gets the Enum values as Dictionary.
/// The Dictionary's Key is the Enum Name or your Description.
/// The Dictionary's Value is the Enum value.
/// </summary>
/// <typeparam name="TEnum">The Enum type.</typeparam>
/// <returns>Returns a dictionary with the Enum values.</returns>
public static IDictionary<string, object> GetValuesAsDictionary<TEnum>() where TEnum : struct, IConvertible
{
Type enumType = typeof(TEnum);
FieldInfo field = null;
var values = new Dictionary<string, object>();
foreach (var enumValue in Enum.GetValues(enumType))
{
field = enumType.GetField(enumValue.ToString());
// Ignore the "None" value.
if (field != null && !field.Name.ToLower(CultureInfo.CurrentCulture).Equals("none"))
{
values.Add(GetEnumValueDescription(field), field.GetRawConstantValue());
}
}
return values;
}
/// <summary>
/// Gets the Enum value description by "DescriptionAttribute" or your name.
/// </summary>
/// <param name="field">The Enum field.</param>
/// <returns>Returns the Enum value description.</returns>
private static string GetEnumValueDescription(FieldInfo field)
{
DescriptionAttribute descriptionAttribute = field.GetCustomAttribute<DescriptionAttribute>(false);
if (descriptionAttribute == null)
{
return field.Name;
}
return descriptionAttribute.Description;
}
}
Helper method for extract the Enum values as Dictionary.
Example:
public enum StudentSituation
{
None = 0,
Active = 1,
Blocked = 2,
Inative = 3
}
IDictionary<string, object> values = EnumHelper.GetValuesAsDictionary<StudentSituation>();
Example:
public enum StudentSituation
{
None = 0,
Active = 1,
Blocked = 2,
Inative = 3
}
IDictionary<string, object> values = EnumHelper.GetValuesAsDictionary<StudentSituation>();
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.