Skip to content

Instantly share code, notes, and snippets.

@cilerler
Created January 21, 2014 19:43
Show Gist options
  • Save cilerler/8546950 to your computer and use it in GitHub Desktop.
Save cilerler/8546950 to your computer and use it in GitHub Desktop.
public class UsingDisplayAttributeOnEnum
{
private void Main()
{
IEnumerable<SelectListItem> result = typeof (Genre).GetItems();
}
}
public enum Genre
{
[Display(Name = "Non Fiction")] NonFiction,
Romance,
Action,
[Display(Name = "Science Fiction")] ScienceFiction
}
public static class EnumHelpers
{
public static IEnumerable<SelectListItem> GetItems(this Type enumType)
{
if (!typeof (Enum).IsAssignableFrom(enumType))
{
throw new ArgumentException("Type must be an enum");
}
string[] names = Enum.GetNames(enumType);
IEnumerable<int> values = Enum.GetValues(enumType).Cast<int>();
IEnumerable<SelectListItem> items = names.Zip(values, (name, value) =>
new SelectListItem
{
Text = GetName(enumType, name),
Value = value.ToString(CultureInfo.InvariantCulture)
});
return items;
}
private static string GetName(Type enumType, string name)
{
string result = name;
DisplayAttribute attribute =
enumType
.GetField(name)
.GetCustomAttributes(false)
.OfType<DisplayAttribute>()
.FirstOrDefault();
if (attribute != null)
{
result = attribute.GetName();
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment