简体   繁体   中英

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.

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.

I only have a Type variable (called enumType ) at runtime.

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). Remember, you don't know about TestEnum at compile time, you only have the variable 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM