I have an enum like this:
enum MyEnum{
[Order(1)]
ElementA = 1,
[Order(0)]
ElementB = 2,
[Order(2)]
ElementC = 3
}
And I want to list its elements sorted by a custom order attribute I wrote, so that I get a list of items sorted.
I am getting the Description Attribute but just for one element like this:
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
It may be something the same but need to work on all Enum and return a list or another sorted enum.
Assume the OrderAttribute
class is as follows:
public class OrderAttribute : Attribute
{
public readonly int Order;
public OrderAttribute(int order)
{
Order = order;
}
}
The helper method to obtain sorted values of enum:
public static T[] SortEnum<T>()
{
Type myEnumType = typeof(T);
var enumValues = Enum.GetValues(myEnumType).Cast<T>().ToArray();
var enumNames = Enum.GetNames(myEnumType);
int[] enumPositions = Array.ConvertAll(enumNames, n =>
{
OrderAttribute orderAttr = (OrderAttribute)myEnumType.GetField(n)
.GetCustomAttributes(typeof(OrderAttribute), false)[0];
return orderAttr.Order;
});
Array.Sort(enumPositions, enumValues);
return enumValues;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With