简体   繁体   中英

Return enum list instead of string in enum extension helper

How can I convert the GetWithOrder methods to return the actual enum in the correct order? It works for the string of the enum, but I want the actual Enum value, plus it needs to be generic of course.

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class EnumOrderAttribute : Attribute
{
    public int Order { get; set; }
}


public static class EnumExtenstions
{
    public static IEnumerable<string> GetWithOrder(this Enum enumVal)
    {
        return enumVal.GetType().GetWithOrder();
    }

    public static IEnumerable<string> GetWithOrder(this Type type)
    {
        if (!type.IsEnum)
        {
            throw new ArgumentException("Type must be an enum");
        }
        // caching for result could be useful
        return type.GetFields()
                               .Where(field => field.IsStatic)
                               .Select(field => new
                                            {
                                                field,
                                                attribute = field.GetCustomAttribute<EnumOrderAttribute>()
                                            })
                                .Select(fieldInfo => new
                                             {
                                                 name = fieldInfo.field.Name,
                                                 order = fieldInfo.attribute != null ? fieldInfo.attribute.Order : 0
                                             })
                               .OrderBy(field => field.order)
                               .Select(field => field.name);
    }
}

public enum TestEnum
{
    [EnumOrder(Order=2)]
    Second = 1,

    [EnumOrder(Order=1)]
    First = 4,

    [EnumOrder(Order=3)]
    Third = 0
}

var names = typeof(TestEnum).GetWithOrder();
var names = TestEnum.First.GetWithOrder();

Extension method for the variable of enum type makes no sense because you don't need a value of that variable - you need only enum type. So I would go with static helper class:

public static class Enum<T>
{
    public static IEnumerable<T> GetOrderedValues()
    {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new InvalidOperationException();

        return from f in type.GetFields(BindingFlags.Static | BindingFlags.Public)
               orderby f.GetCustomAttribute<EnumOrderAttribute>()?.Order ?? Int32.MaxValue
               select (T)f.GetValue(obj: null);
    }
}

Note: enum type has a non-static value field which actually holds the value of the enum. So you need to take only static fields if you want to list enum members.

Usage

var values = Enum<Fruits>.GetOrderedValues();

For sample enum

public enum Fruits
{
    Banana,
    [EnumOrder(2)]
    Apple,
    [EnumOrder(1)]
    Lemon
}

Output will be

[ Lemon, Apple, Banana ]

Members without EnumOrder attribute will go last, but you can change that behavior if you'll use some other default order instead of Int32.MaxValue .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM