[英]How to sort the result of Enum.GetValues without knowing the Enum itself
I'm looking for a way to sort the result of [Enum].GetValues(enumType)
(which is an Array
) by the enum values names. 我正在寻找一种通过枚举值名称对
[Enum].GetValues(enumType)
(这是一个Array
)的结果进行排序的方法。
Public Enum TestEnum As Integer
Zero = 0
One = 1
Two = 2
End Enum
I don't know the enum type at compile time, so I can't do a Cast(Of...)
on the Array
and use the OrderBy
extension after that. 我不知道在编译时的枚举类型,所以我不能在
Array
上执行Cast(Of...)
,然后再使用OrderBy
扩展。
I only have a Type
variable (called enumType
) at runtime. 我在运行时只有一个
Type
变量(称为enumType
)。
Dim enumType As Type = GetType(TestEnum) 'just for testing
Dim values As Array = [Enum].GetValues(enumType)
The values
array contains {Zero, One, Two} and I'm looking for a way to get to {One, Two, Zero} (alphabetical order). values
数组包含{Zero,One,Two}(零,一,二),我正在寻找一种方法来达到{One,Two,Zero}(字母顺序)。 Remember, you don't know about TestEnum
at compile time, you only have the variable enumType
. 记住,您在编译时不了解
TestEnum
,只有变量enumType
。
I was hoping for a more elegant solution, but this will do: 我希望有一个更优雅的解决方案,但这可以做到:
Dim enumType As Type = GetType(TestEnum)
Dim names As String() = [Enum].GetNames(enumType)
Dim values As Array = names.OrderBy(Of String)(Function(x As String) x) _
.Select(Of Object)((Function(x As String) [Enum].Parse(enumType, x))) _
.ToArray
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.