Skip to content

Instantly share code, notes, and snippets.

@stevehobbsdev
Created March 30, 2016 09:53
Show Gist options
  • Save stevehobbsdev/383876a2e7af6dc4566c38cb7ad6dbf1 to your computer and use it in GitHub Desktop.
Save stevehobbsdev/383876a2e7af6dc4566c38cb7ad6dbf1 to your computer and use it in GitHub Desktop.
IEnumerable<T> GetEnumOrder<T>()
{
var type = typeof(T);
var tmp = new List<dynamic>();
foreach (var value in Enum.GetValues(type))
{
var attr = type.GetMember(value.ToString())[0].GetCustomAttribute(typeof(DisplayAttribute), false) as DisplayAttribute;
tmp.Add(new
{
Value = (T)value,
Order = attr?.Order ?? 9999
});
}
return tmp
.OrderBy(t => t.Order)
.Select(t => t.Value)
.Cast<T>()
.ToArray();
}
enum TestEnum
{
[Display(Order = 0)]
One,
[Display(Order = 2)]
Two,
[Display(Order = 1)]
Three
}
@stevehobbsdev
Copy link
Author

Usage:

var list = GetEnumOrder<TestEnum>();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment