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?
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);
}
}
}
}
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.
IEnumerable<T>.OrderBy(Func<T, TKey>, IComparer<TKey>)
Sort FileSystemRights enum using Linq and bind to WinForms comboBox:
comboBox1.DataSource = ((FileSystemRights[])Enum.GetValues(typeof(FileSystemRights))).
OrderBy(p => p.ToString()).ToArray();
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.