Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort enum using a custom order attribute?

Tags:

c#

enums

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.

like image 575
Amr Elgarhy Avatar asked Jun 04 '15 21:06

Amr Elgarhy


1 Answers

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;
}
like image 97
Dmitry Avatar answered Sep 20 '22 00:09

Dmitry