user3835485
user3835485

Reputation:

Alternative method to check whether a number is present in a given range or not?

If i want to check a number(X) in between certain limit (55 -100) then i need to check with the following condition

If x >= 55 and x <= 100 then
    MsgBox("Number is within the given Range")
Else
    MsgBox("Number is not within the given Range")
End If

is their any simplest way to check this?

like BETWEEN in SQL as

x BETWEEN 55 and 100

Upvotes: 0

Views: 130

Answers (3)

An alternative way is to create a generic extension method constrained by the IComparable<T> interface. It's implemented by all of the primitive types (++).

Public Module Extensions

    <Runtime.CompilerServices.Extension()>
    Public Function Between(Of T As IComparable(Of T))(value As T, minimum As T, maximum As T) As Boolean
        Return (value.CompareTo(minimum) >= 0) AndAlso (value.CompareTo(maximum) <= 0)
    End Function

End Module

Usage:

If x.Between(55, 100) Then
Else
End If

Upvotes: 1

user3972104
user3972104

Reputation:

I think their is no such operator is available, You can use SELECT CASE instead for this as an alternative.

 Dim x As Integer = 72
 Select Case x
    Case 55 To 100
        MsgBox("Number is within the given Range")
     Case Else
        MsgBox("Number is not within the given Range")
 End Select 

Or in another way you can use Enumerable Range

 Dim x As Integer = 72
 Dim rng = Enumerable.Range(200, 200)
 If rng.Contains(x) Then
    MsgBox("Number is within the given Range")
 Else
    MsgBox("Number is not within the given Range")
 End If

Both can't be say as a simplest method but an alternative method for this

Upvotes: 0

Matt Wilko
Matt Wilko

Reputation: 27322

You want a Select Case Statement:

    Select Case x
        Case 55 To 100
            MsgBox("Number is within the given Range")
        Case Else
            MsgBox("Number is not within the given Range")
    End Select

Upvotes: 2

Related Questions