paulopulus
paulopulus

Reputation: 221

Check whether a string is not equal to any of a list of strings

Is there a way to convert some code like this:

If someString <> "02" And someString <> "03" And someString <> "06" And someString <> "07" Then
     btnButton.Enabled = False
End If

kinda into something like this (multiple values for one variable)

If someString <> "02", "03", "06", "07" Then
     btnButton.Enabled = False
End If

Upvotes: 16

Views: 37226

Answers (4)

stonypaul
stonypaul

Reputation: 677

How about this?

Imports System.Text.RegularExpressions    

btnButton.Enabled = Regex.IsMatch(someString, "^0[2367]$")

Upvotes: 0

Fabian Tamp
Fabian Tamp

Reputation: 4526

Would Contains work?

Dim testAgainst As String() = {"02","03","06","07"}
If Not testAgainst.Contains(someString) Then
    btnButton.Enabled = False
End If

Upvotes: 27

Johnno Nolan
Johnno Nolan

Reputation: 29659

Dim invalidvalues As New List(Of String) From { _
    "02", _
    "03,", _
    "04", _
    "07" _
}

If invalidvalues.Contains(x) Then
    btnButton.Enabled = False
End If

Upvotes: 5

Ry-
Ry-

Reputation: 224952

You can (ab)use Select for this in simple cases:

Select Case someString
    Case "02", "03", "06", "07"
    Case Else
        btnButton.Enabled = False
End Select

Also, a common extension that I use is:

<Extension()>
Function [In](Of TItem, TColl)(this As TItem, ParamArray items() As TColl)
    Return Array.IndexOf(items, this) > -1
End Function

So:

If Not someString.In("02", "03", "06", "07") Then
    btnButton.Enabled = False
End If

Upvotes: 15

Related Questions