假設我們有一個用戶界面,並且在此用戶界面中有一個下拉菜單。該下拉列表中填入了enum的翻譯值。爲用戶界面排序枚舉
鞠躬,我們有可能通過枚舉的int值,枚舉的名稱和enum的已翻譯名稱進行排序。
但是,如果我們想要一個不同於上述3的排序呢。如何處理這樣的要求?
假設我們有一個用戶界面,並且在此用戶界面中有一個下拉菜單。該下拉列表中填入了enum的翻譯值。爲用戶界面排序枚舉
鞠躬,我們有可能通過枚舉的int值,枚舉的名稱和enum的已翻譯名稱進行排序。
但是,如果我們想要一個不同於上述3的排序呢。如何處理這樣的要求?
實現自己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);
}
}
}
}
IEnumerable<T>.OrderBy(Func<T, TKey>, IComparer<TKey>)
可以使用LINQ的擴展OrderBy
,並執行任何你想要的比較法寶:
// order by the length of the value
SomeEnum[] values = (SomeEnum[])Enum.GetValues(typeof(SomeEnum));
IEnumerable<SomeEnum> sorted = values.OrderBy(v => v.ToString().Length);
然後敷不同的排序方案進入方法,並調用根據用戶的喜好是正確的/輸入。
Perhapse你可以創建爲枚舉類的擴展方法,像這樣:
...先聲明......
public enum MyValues { adam, bertil, caesar };
...然後在方法中...
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;
}
}
而且你可以到擴展梅託德的使用LINQ不同的排序選項等
排序FileSystemRights枚舉添加不同的參數並綁定到的WinForms組合框:
comboBox1.DataSource = ((FileSystemRights[])Enum.GetValues(typeof(FileSystemRights))).
OrderBy(p => p.ToString()).ToArray();
那會是什麼樣的排序嗎? – 2009-08-19 10:43:44
一個有用的:)通常是由另一個人認爲它應該在某種方式(除開發商設置int值的方式) – karlis 2009-08-19 10:45:45