tags:

views:

553

answers:

4

say we have a ui and in this ui we have a dropdown. this dropdown is filled with the translated values of an enum.

now, 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?

A: 

IEnumerable<T>.OrderBy(Func<T, TKey>, IComparer<TKey>)

Mark Seemann
A: 

You can use the Linq extension OrderBy, and perform whatever comparison magic you want:

// order by the length of the value 
SomeEnum[] values = (SomeEnum[])Enum.GetValues(typeof(SomeEnum));
IEnumerable<SomeEnum> sorted = values.OrderBy(v => v.ToString().Length);

Then wrap the different sorting alternatives into methods, and invoke the right one based on user preferences/input.

Fredrik Mörk
+2  A: 

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);
            }
        }
    }
}
Paolo Tedesco
A: 

Perhapse you could create an extension method for the Enum class, like this:

... first the declaration...

public enum MyValues { adam, bertil, caesar };

...then in a method...

MyValues values = MyValues.adam;
string[] forDatabinding = values.SpecialSort("someOptions");

...The extension method... 

public static class Utils
    {
        public static string[] SpecialSort(this MyValues theEnum, string someOptions)
        {
            //sorting code here;
        }
    }

And you could add different parameters to the extension metod for different sort options etc.

kaze