SORT ENUMS IN DECLARATION ORDER

Manoj Bhatt

Total Post:154

Points:1086
Posted by  Manoj Bhatt
C# 
C#
 1278  View(s)
Ratings:
Rate this:
public enum CurrencyId
{
    USD = 840,
    UAH = 980,
    RUR = 643,
    EUR = 978,
    KZT = 398,
    UNSUPPORTED = 0
}

Is there any way to sort results of Enum.GetValues(typeof(CurrencyId)).Cast<CurrencyId>() by order they are declared in .cs file (USD, UAH, RUR, EUR, KZT, UNSUPPORTED), not by their underlying code? Personally, I believe the answer is 'no', because original order is lost in binaries, so... how can I implement the task?

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Sort enums in declaration order

    Hi Manoj, 

    try this:

    using System;
    using System.Reflection;
    public class Test
    {
        public enum CurrencyId {
            USD = 840,
            UAH = 980,
            RUR = 643,
            EUR = 978,
            KZT = 398,
            UNSUPPORTED =0
        }
        public static void Main()
        {
            foreach(FieldInfo fi in typeof(CurrencyId).GetFields())
                if(fi.IsStatic) Console.WriteLine(fi.Name);
        }
    }

    Output:

    USD

    UAH

    RUR

    EUR

    KZT

      Modified On Apr-04-2018 05:42:18 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!