Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
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()));
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;
return value.ToString();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.