Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to retrieve the enum members in the order they have been defined!

We have an enum with members having random values, say

enum MyEnum
{
    enumMember1 = 100,
    enumMember2 = 10,
    enumMember3 = 50
}

We couldnt iterate through the enum members in the order they have been defined! Enum.GetValues and Enum.GetNames both internally sort the members and gives the result!

iterating the array returned by Enum.GetNames or Enum.GetValues and doing a .ToString() on each of the array elements gives us,

enumMember2, enumMember3, enumMember100. 

Was just wondering if there is any out of the box approach to get the enum members in the order they have been created? Did search, didnt get much info! Thanks!

P.S. I would hate to get this done through a custom attribute! And While drafting it, i had a doubt if the IL for enum gets generated after sorting the Enum members, going to check it ryt away!

like image 747
ioWint Avatar asked Jul 06 '11 19:07

ioWint


1 Answers

You can use reflection:

var values = typeof(MyEnum).GetFields(BindingFlags.Public | BindingFlags.Static)
                 .Select (x => Enum.Parse(typeof(MyEnum), x.Name));
like image 116
Magnus Avatar answered Oct 10 '22 11:10

Magnus