创建enum列表,其中包含enum中的位置顺序,而不是值

时间:2017-10-06 14:18:32

标签: c# .net enums

以下代码始终按enum的值排序,但我想按enum中的位置进行排序。您注意到Matchupenum中排名第三,但值为6.它始终位于列表中最后一位的迭代中。

 foreach (var enumName in Enum.GetValues(enumType).Cast<TEnum>())
            {

}

 public enum RestrictionDetailType
    {
        [EnumMember(Value = "0"), Display(Name = "None")]
        None = 0,
        [EnumMember(Value = "1"), Display(Name = "Team")]
        Team = 1,
        [EnumMember(Value = "6"), Display(Name = "Matchup")]
        Matchup = 6,
        [EnumMember(Value = "2"), Display(Name = "Date/Time")]
        DateTime = 2,
        [EnumMember(Value = "3"), Display(Name = "Venue")]
        VenueCourt = 3,
        [EnumMember(Value = "4"), Display(Name = "Games")]
        Games = 4,
        [EnumMember(Value = "5"), Display(Name = "Exhibition")]
        Exhibition = 5
    }

2 个答案:

答案 0 :(得分:3)

foreach(FieldInfo fi in typeof(RestrictionDetailType).GetFields()
  .Where(fi => fi.IsStatic).OrderBy(fi => fi.MetadataToken))
    Console.WriteLine(fi.Name);

来源:Sort enums in declaration order

答案 1 :(得分:1)

您可以编写自己的方法,如下所示:

public static List<T> GetEnumValuesInDeclarationOrder<T>()
{
    var t = typeof(T);
    // first type in this array is the data-type of the enum, int32 if not defined
    var members = t.GetFields();

    var result = new List<T>(members.Length - 1);
    foreach (FieldInfo mem in members.Skip(1))
        result.Add((T)mem.GetValue(null));

    return result;
}