By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,640 Members | 1,598 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,640 IT Pros & Developers. It's quick & easy.

Compare a Variable Against Multiple Values

P: n/a
Is there a mechanism in VB.NET that allows something like:

If myVar In ("A","B","C") Then...

The way I'm doing it now is:

Select Case myVar
Case "A","B","C"

Or like this:

If myVar = "A" Or myVar = "B" Or myVar = "C" Then...

I'm just wondering if there's some handy new syntax in .NET to handle this.
Nov 21 '05 #1
Share this Question
Share on Google+
5 Replies


P: n/a
"Jason" <so*****@microsoft.com> schrieb:
Is there a mechanism in VB.NET that allows something like:

If myVar In ("A","B","C") Then...

The way I'm doing it now is:

Select Case myVar
Case "A","B","C"

Or like this:

If myVar = "A" Or myVar = "B" Or myVar = "C" Then...

I'm just wondering if there's some handy new syntax in .NET to handle
this.


There is no new syntax to do that. I prefer the 'Select Case' solution.
Alternatively you can check if an object is contained in an array using
'Array.IndexOf'.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>

Nov 21 '05 #2

P: n/a
Jason,

Have a look to the endless amount of IndexOf methods, that is the nearest
I can think about trying to understand what you want to achieve.

One of them is according to your sample.

http://msdn.microsoft.com/library/de...exoftopic1.asp

I hope this helps.

Cor
Nov 21 '05 #3

P: n/a
Jason,
In addition to the other comments:
If myVar = "A" Or myVar = "B" Or myVar = "C" Then... Consider using OrElse instead of Or, as Or will cause all the equations to
be evaluated before returning a result, OrElse will return the result after
the first match. For example, if myVar = "A":
If myVar = "A" Or myVar = "B" Or myVar = "C" Then... Will compare myVar, to "A", then to "B", the to "C" before it returns True.

Where as:
If myVar = "A" OrElse myVar = "B" OrElse myVar = "C" Then... Will compare myVar to "A", and return True! (checking for "B" or "C" is not
needed as "A" is True!)

---x--- begin earlier post of mine ---x---
I would use the RegEx as its IMHO the "simplest" & "cleanest"
implementation! However! you need to understand RegEx to be comfortable
using it, luckily this regex is easy. Also you may need to get over the
perception that RegEx is slow. Yes it has some inherit overhead the other
methods do not, however that overhead may be warranted for the simplicity of
the routine. Also based on the context the overhead of the RegEx may be
lower, significantly lower, then other routines.

Note: I would only use the RegEx method for checking Strings, if I was
creating an "In" for other types I would pick an algorithm that was more
friendly for that type.

Here's one possibility for an "In" function based on RegEx.

Public Shared Function [In](ByVal input As String, ByVal ParamArray
words() As String) As Boolean
Dim pattern As String = String.Join("|", words)
Return System.Text.RegularExpressions.Regex.IsMatch(input , pattern)
End Function

Then to use it you simple need to:

strTest = "The cat jumped over the sleepy dog."
If [In](strTest, "cat","dog", "sleep") Then
Debug.WriteLine("Found strings")
Else
Debug.WriteLine("Did NOT find strings!")
End If

If the above RegEx version proved to be a performance problem I would then
consider using a For Each loop.

Public Shared Function [In](ByVal input As String, ByVal ParamArray
words() As String) As Boolean
For Each word As String In words
If input.IndexOf(word) <> -1 Then
Return True
End If
Next
Return False
End Function

I would consider creating an object that contained a list of words, which
had a method the checked to see if a string had one of those words.

Public Class ValidValues

Private ReadOnly m_regex As System.Text.RegularExpressions.Regex

Public Sub New(ByVal ParamArray words() As String)
Dim pattern As String = String.Join("|", words)
m_regex = New System.Text.RegularExpressions.Regex(pattern,
System.Text.RegularExpressions.RegexOptions.Compil ed)
End Sub

Public Function IsMatch(ByVal value As String) As Boolean
Return m_regex.IsMatch(value)
End Function

End Class
Dim values As New ValidValues("cat", "dog", "sleep")
If values.IsMatch(strTest) Then
Debug.WriteLine("Found strings")
Else
Debug.WriteLine("Did NOT find strings!")
End If
Return

Dim statusValues As New ValidValues("ACTIVE","OTHER")
If statusValues.IsMatch(Status) Then
...

Notice in both cases that the actual method (algorithm) of matching is
hidden (encapsulated) within either the object or the function itself. Which
allows you to replace the Algorithm with a more efficient one if needed...

Whether I used the Function or Class would depend on how the function or
class was being within my program... Using Refactoring
http://www.refactoring.com I can change between the two...

As the others pointed out there are other equally valid ways to implement
the above. There are also methods that have yet to be mentioned, such as
using a HashTable or using a DataSet, plus still others. Which one you
should use REALLY depends on the context of what you are doing!

For example if your status value is in a DataTable, you can use a filter
statement that include an "In" statement, on either DataTable.Select or
DataView.RowFilter. Like wise of the list of valid statues are in a
DataTable, you could use DataTable.Rows.Find assuming that the status was
the primary key to that table, or use filter & either DataTable.Select or
DataView.RowFilter...

Hope this helps
Jay

---x--- end earlier post of mine ---x---

Another example routine:

Public Shared Function IsInSet(ByVal item As Object, ByVal ParamArray
setItems() As Object) As Boolean
Return (Array.IndexOf(SetItems, Item) >= 0)
End Function
Hope this helps
Jay

"Jason" <so*****@microsoft.com> wrote in message
news:eg**************@TK2MSFTNGP14.phx.gbl... Is there a mechanism in VB.NET that allows something like:

If myVar In ("A","B","C") Then...

The way I'm doing it now is:

Select Case myVar
Case "A","B","C"

Or like this:

If myVar = "A" Or myVar = "B" Or myVar = "C" Then...

I'm just wondering if there's some handy new syntax in .NET to handle
this.

Nov 21 '05 #4

P: n/a
I have been trying to figure this out too. The regex you have for
testing individual words is what I came up with too. Unfortunately, it
also matches partial strings like catdog, dogcat, catty. Any tricks to
forcing "whole word" logic?

"Jay B. Harlow [MVP - Outlook]" <Ja************@msn.com> wrote in message news:<O5**************@TK2MSFTNGP10.phx.gbl>...
Jason,
In addition to the other comments:
If myVar = "A" Or myVar = "B" Or myVar = "C" Then...

Consider using OrElse instead of Or, as Or will cause all the equations to
be evaluated before returning a result, OrElse will return the result after
the first match. For example, if myVar = "A":
If myVar = "A" Or myVar = "B" Or myVar = "C" Then...

Will compare myVar, to "A", then to "B", the to "C" before it returns True.

Where as:
If myVar = "A" OrElse myVar = "B" OrElse myVar = "C" Then...

Will compare myVar to "A", and return True! (checking for "B" or "C" is not
needed as "A" is True!)

---x--- begin earlier post of mine ---x---
I would use the RegEx as its IMHO the "simplest" & "cleanest"
implementation! However! you need to understand RegEx to be comfortable
using it, luckily this regex is easy. Also you may need to get over the
perception that RegEx is slow. Yes it has some inherit overhead the other
methods do not, however that overhead may be warranted for the simplicity of
the routine. Also based on the context the overhead of the RegEx may be
lower, significantly lower, then other routines.

Note: I would only use the RegEx method for checking Strings, if I was
creating an "In" for other types I would pick an algorithm that was more
friendly for that type.

Here's one possibility for an "In" function based on RegEx.

Public Shared Function [In](ByVal input As String, ByVal ParamArray
words() As String) As Boolean
Dim pattern As String = String.Join("|", words)
Return System.Text.RegularExpressions.Regex.IsMatch(input , pattern)
End Function

Then to use it you simple need to:

strTest = "The cat jumped over the sleepy dog."
If [In](strTest, "cat","dog", "sleep") Then
Debug.WriteLine("Found strings")
Else
Debug.WriteLine("Did NOT find strings!")
End If

If the above RegEx version proved to be a performance problem I would then
consider using a For Each loop.

Public Shared Function [In](ByVal input As String, ByVal ParamArray
words() As String) As Boolean
For Each word As String In words
If input.IndexOf(word) <> -1 Then
Return True
End If
Next
Return False
End Function

I would consider creating an object that contained a list of words, which
had a method the checked to see if a string had one of those words.

Public Class ValidValues

Private ReadOnly m_regex As System.Text.RegularExpressions.Regex

Public Sub New(ByVal ParamArray words() As String)
Dim pattern As String = String.Join("|", words)
m_regex = New System.Text.RegularExpressions.Regex(pattern,
System.Text.RegularExpressions.RegexOptions.Compil ed)
End Sub

Public Function IsMatch(ByVal value As String) As Boolean
Return m_regex.IsMatch(value)
End Function

End Class
Dim values As New ValidValues("cat", "dog", "sleep")
If values.IsMatch(strTest) Then
Debug.WriteLine("Found strings")
Else
Debug.WriteLine("Did NOT find strings!")
End If
Return

Dim statusValues As New ValidValues("ACTIVE","OTHER")
If statusValues.IsMatch(Status) Then
...

Notice in both cases that the actual method (algorithm) of matching is
hidden (encapsulated) within either the object or the function itself. Which
allows you to replace the Algorithm with a more efficient one if needed...

Whether I used the Function or Class would depend on how the function or
class was being within my program... Using Refactoring
http://www.refactoring.com I can change between the two...

As the others pointed out there are other equally valid ways to implement
the above. There are also methods that have yet to be mentioned, such as
using a HashTable or using a DataSet, plus still others. Which one you
should use REALLY depends on the context of what you are doing!

For example if your status value is in a DataTable, you can use a filter
statement that include an "In" statement, on either DataTable.Select or
DataView.RowFilter. Like wise of the list of valid statues are in a
DataTable, you could use DataTable.Rows.Find assuming that the status was
the primary key to that table, or use filter & either DataTable.Select or
DataView.RowFilter...

Hope this helps
Jay

---x--- end earlier post of mine ---x---

Another example routine:

Public Shared Function IsInSet(ByVal item As Object, ByVal ParamArray
setItems() As Object) As Boolean
Return (Array.IndexOf(SetItems, Item) >= 0)
End Function
Hope this helps
Jay

"Jason" <so*****@microsoft.com> wrote in message
news:eg**************@TK2MSFTNGP14.phx.gbl...
Is there a mechanism in VB.NET that allows something like:

If myVar In ("A","B","C") Then...

The way I'm doing it now is:

Select Case myVar
Case "A","B","C"

Or like this:

If myVar = "A" Or myVar = "B" Or myVar = "C" Then...

I'm just wondering if there's some handy new syntax in .NET to handle
this.

Nov 21 '05 #5

P: n/a
post messages,
The string "catdog" includes both "cat" & "dog" I don't see it as an error
per se...
Any tricks to
forcing "whole word" logic? You could build the pattern such that each specific word needs non word \W
delimiters around it, or be at the beginning or end of the string.

Try something like:

Public Function [In](ByVal input As String, ByVal ParamArray words() As
String) As Boolean
Dim pattern As String = "(^|\W+)(" & String.Join("|", words) &
")($|\W+)"
Return System.Text.RegularExpressions.Regex.IsMatch(input , pattern)
End Function

Hope this helps
Jay

"post messages" <po***********@gmail.com> wrote in message
news:c4**************************@posting.google.c om...I have been trying to figure this out too. The regex you have for
testing individual words is what I came up with too. Unfortunately, it
also matches partial strings like catdog, dogcat, catty. Any tricks to
forcing "whole word" logic?

<<snip>>
Nov 21 '05 #6

This discussion thread is closed

Replies have been disabled for this discussion.