Skip to content

Instantly share code, notes, and snippets.

@bcronje
Created October 2, 2012 13:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcronje/3819117 to your computer and use it in GitHub Desktop.
Save bcronje/3819117 to your computer and use it in GitHub Desktop.
Enum ToSelectList extensions with DisplayAttribute support
public static class EnumExtensions
{
public static SelectList ToSelectList<T>(T? defaultValue) where T : struct
{
Type t = typeof(T);
if (t.IsEnum)
{
var values = from Enum e in Enum.GetValues(t)
select new
{
ID = Enum.Parse(typeof(T), e.ToString()),
Description = GetEnumDescription(e)
};
if (defaultValue.HasValue)
return new SelectList(values, "ID", "Description", Enum.Parse(typeof(T), defaultValue.ToString()));
else
return new SelectList(values, "ID", "Description");
}
return null;
}
public static string GetEnumDescription<T>(T value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DisplayAttribute[] attributes = (DisplayAttribute[])fi.GetCustomAttributes(typeof(DisplayAttribute), false);
if ((attributes != null) && (attributes.Length > 0))
return attributes[0].Name;
else
return value.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment