按字母顺序排序typeof(EnumType)的有效方法是什么?
枚举值具有非顺序索引,但按字母顺序排序.(即苹果= 5,香蕉= 2,哈密瓜= 3)
临时实例化很好.
最终我需要所选特定枚举值的索引代码.
我问,因为我提出的方法看起来并不是最好的:
Array tmp = Enum.GetValues(typeof(EnumType));
string[] myenum = tmp.OfType<object>().Select(o => o.ToString()).ToArray();
Array.Sort(myenum);
int enum_code = (int)Enum.Parse(typeof(EnumType), myenum.GetValue((int)selected_index).ToString());
string final_code = enum_code.ToString());
Run Code Online (Sandbox Code Playgroud)
您可以使用Linq编写更紧凑和可维护的代码.除非你在高性能应用程序的内部循环中执行此操作,否则我怀疑Linq与原始代码相比其他任何可能实现的速度都很重要:
var sorted = (from e in Enum.GetValues(typeof(EnumType)).Cast<EnumType>()
orderby e.ToString() select e).ToList();
Run Code Online (Sandbox Code Playgroud)