karlis
karlis

Reputation: 920

sorting enum for UI purpose

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?

Upvotes: 12

Views: 11305

Answers (5)

Jochen Scharr
Jochen Scharr

Reputation: 695

Sort FileSystemRights enum using Linq and bind to WinForms comboBox:

comboBox1.DataSource = ((FileSystemRights[])Enum.GetValues(typeof(FileSystemRights))).
 OrderBy(p => p.ToString()).ToArray();

Upvotes: 1

kaze
kaze

Reputation: 4359

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.

Upvotes: 0

Fredrik Mörk
Fredrik Mörk

Reputation: 158399

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.

Upvotes: 9

Paolo Tedesco
Paolo Tedesco

Reputation: 57302

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);
            }
        }
    }
}

Upvotes: 11

Mark Seemann
Mark Seemann

Reputation: 233497

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

Upvotes: 3

Related Questions