The next code illustrates how to find the nearest value of a Enum.
First we define this Enum that will serve to specify search criteria (search direction)
Public Enum EnumFindDirection As Integer
Nearest = 0
Less = 1
LessOrEqual = 2
Greater = 3
GreaterOrEqual = 4
End Enum
And now we implement the search algorithm:
<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
Usage Example:
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)