Sort enums in declaration order

前端 未结 2 1477
粉色の甜心
粉色の甜心 2020-12-10 06:11
public enum CurrencyId
{
    USD = 840,
    UAH = 980,
    RUR = 643,
    EUR = 978,
    KZT = 398,
    UNSUPPORTED = 0
}

Is there any way to sort

2条回答
  •  情书的邮戳
    2020-12-10 06:46

    Here is version with custom attribute:

    [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
    public class EnumOrderAttribute : Attribute
    {
        public int Order { get; set; }
    }
    
    
    public static class EnumExtenstions
    {
        public static IEnumerable GetWithOrder(this Enum enumVal)
        {
            return enumVal.GetType().GetWithOrder();
        }
    
        public static IEnumerable 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()
                                                })
                                    .Select(fieldInfo => new
                                                 {
                                                     name = fieldInfo.field.Name,
                                                     order = fieldInfo.attribute != null ? fieldInfo.attribute.Order : 0
                                                 })
                                   .OrderBy(field => field.order)
                                   .Select(field => field.name);
        }
    }
    

    Usage:

    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();
    

提交回复
热议问题