Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting enum for UI purpose

Tags:

c#

enums

asp.net

Say we have a UI and in this UI we have a dropdown. This dropdown is filled with the translated values of an enum.

Bow, we have the possibility to sort by the int-value of the enum, by the name of the enum, and by the translated name of the enum.

But what if we want a different sorting than the 3 mentioned above. how to handle such a requirement?

like image 899
karlis Avatar asked Aug 19 '09 10:08

karlis


1 Answers

Implement your own IComparer:

using System;
using System.Collections.Generic;

namespace test {
    class Program {

        enum X { 
            one,
            two,
            three,
            four
        }

        class XCompare : IComparer<X> {
            public int Compare(X x, X y) {
                // TBA: your criteria here
                return x.ToString().Length - y.ToString().Length;
            }
        }


        static void Main(string[] args) {
            List<X> xs = new List<X>((X[])Enum.GetValues(typeof(X)));
            xs.Sort(new XCompare());
            foreach (X x in xs) {
                Console.WriteLine(x);
            }
        }
    }
}
like image 109
Paolo Tedesco Avatar answered Sep 21 '22 17:09

Paolo Tedesco