以下代码始终按enum
的值排序,但我想按enum
中的位置进行排序。您注意到Matchup
在enum
中排名第三,但值为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
}
答案 0 :(得分:3)
foreach(FieldInfo fi in typeof(RestrictionDetailType).GetFields()
.Where(fi => fi.IsStatic).OrderBy(fi => fi.MetadataToken))
Console.WriteLine(fi.Name);
答案 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;
}