Created
January 21, 2014 19:43
-
-
Save cilerler/8546950 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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