在枚举中找到最接近的值
下一个代码说明了如何找到最接近的枚举值。
首先,我们定义此 Enum ,用于指定搜索条件(搜索方向)
Public Enum EnumFindDirection As Integer
Nearest = 0
Less = 1
LessOrEqual = 2
Greater = 3
GreaterOrEqual = 4
End Enum
现在我们实现搜索算法:
<DebuggerStepThrough>
Public Shared Function FindNearestEnumValue(Of T)(ByVal value As Long,
ByVal direction As EnumFindDirection) As T
Select Case direction
Case EnumFindDirection.Nearest
Return (From enumValue As T In [Enum].GetValues(GetType(T)).Cast(Of T)()
Order By Math.Abs(value - Convert.ToInt64(enumValue))
).FirstOrDefault
Case EnumFindDirection.Less
If value < Convert.ToInt64([Enum].GetValues(GetType(T)).Cast(Of T).First) Then
Return [Enum].GetValues(GetType(T)).Cast(Of T).FirstOrDefault
Else
Return (From enumValue As T In [Enum].GetValues(GetType(T)).Cast(Of T)()
Where Convert.ToInt64(enumValue) < value
).LastOrDefault
End If
Case EnumFindDirection.LessOrEqual
If value < Convert.ToInt64([Enum].GetValues(GetType(T)).Cast(Of T).First) Then
Return [Enum].GetValues(GetType(T)).Cast(Of T).FirstOrDefault
Else
Return (From enumValue As T In [Enum].GetValues(GetType(T)).Cast(Of T)()
Where Convert.ToInt64(enumValue) <= value
).LastOrDefault
End If
Case EnumFindDirection.Greater
If value > Convert.ToInt64([Enum].GetValues(GetType(T)).Cast(Of T).Last) Then
Return [Enum].GetValues(GetType(T)).Cast(Of T).LastOrDefault
Else
Return (From enumValue As T In [Enum].GetValues(GetType(T)).Cast(Of T)()
Where Convert.ToInt64(enumValue) > value
).FirstOrDefault
End If
Case EnumFindDirection.GreaterOrEqual
If value > Convert.ToInt64([Enum].GetValues(GetType(T)).Cast(Of T).Last) Then
Return [Enum].GetValues(GetType(T)).Cast(Of T).LastOrDefault
Else
Return (From enumValue As T In [Enum].GetValues(GetType(T)).Cast(Of T)()
Where Convert.ToInt64(enumValue) >= value
).FirstOrDefault
End If
End Select
End Function
用法示例:
Public Enum Bitrate As Integer
Kbps128 = 128
Kbps192 = 192
Kbps256 = 256
Kbps320 = 320
End Enum
Dim nearestValue As Bitrate = FindNearestEnumValue(Of Bitrate)(224, EnumFindDirection.GreaterOrEqual)