我有这个枚举:
Enum Lame_Bitrate
kbps_8 = 8
kbps_16 = 16
kbps_24 = 24
kbps_32 = 32
kbps_40 = 40
kbps_48 = 48
kbps_56 = 56
kbps_64 = 64
kbps_80 = 80
kbps_96 = 96
kbps_112 = 112
kbps_128 = 128
kbps_144 = 144
kbps_160 = 160
kbps_192 = 192
kbps_224 = 224
kbps_256 = 256
kbps_320 = 320
End Enum
我想返回给定数字的枚举的近似值。
例如,如果我有数字190
,那么我希望在枚举中找到更近似的值以返回192
(枚举的kbps_192值),如果我有数字196
,那么我再次期望返回值192
(不返回下一个值224
,因为不太近似)。
类似这样的事情:
Private Sub Test()
Dim wma_file As String = "C:\windows media audio file.wma"
Dim wma_file_Bitrate As Integer = 172
Dim mp3_bitrate_approximated As Integer
mp3_bitrate_approximated = Return_Approximated_Value_Of_Enum(wma_file_Bitrate)
End Sub
private function Return_Approximated_Value_Of_Enum(byval value as integer) as integer
return... enum.find(value).approximated...
end function
是否存在任何框架方法来查找枚举中给定其他数字的更近似数字?
希望您能理解我的问题,谢谢。
PS:如果可以的话,我更喜欢使用 LINQ 扩展的解决方案。
最佳答案
如果你想找到最近的枚举:
Dim number = 190
Dim allBitrates() As Lame_Bitrate = DirectCast([Enum].GetValues(GetType(Lame_Bitrate)), Lame_Bitrate())
Dim nearestBitrate = allBitrates.OrderBy(Function(br) Math.Abs(number - br)).First()
如果您想查找所有最近的枚举(如果有多个具有相同最小距离的枚举):
number = 120 ' two with the same distance
Dim nearestBitrates As IEnumerable(Of Lame_Bitrate) = allBitrates.
GroupBy(Function(br) Math.Abs(number - br)).
OrderBy(Function(grp) grp.Key).
First()
Console.Write(String.Join(",", nearestBitrates))
输出:
kbps_112,kbps_128
关于.net - 给出一个数字以返回 Enum 的近似值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19717124/