473,322 Members | 1,480 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

Compare a Variable Against Multiple Values

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
5 37671
"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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: Roland Hall | last post by:
Is there a way to return multiple values from a function without using an array? Would a dictionary object work better? -- Roland Hall /* This information is distributed in the hope that it...
2
by: Chaz | last post by:
Hello, I hope someone can help me out. I am going to be taking the third step in a programming class soon(I took the previous two a while ago at a different school) and in an effort to get back up...
0
by: RJN | last post by:
Hi My web service receives an object of type say MyObject. I want to serialize this object,and then validate the xml against the main xsd. When validation happens, it should also validate...
0
by: RJN | last post by:
hi My web service receives an object of type say MyObject. I want to serialize this object,and then validate the xml against the main xsd. When validation happens, it should also validate...
8
by: Chris A via AccessMonster.com | last post by:
I have an interesting problem that I have yet to come accross that I can't change data structure on because it is an export from filemaker I am reformatting for another dept. anyway. I have a table...
5
by: paul_zaoldyeck | last post by:
does anyone know how to validate an xml file against multiple defined schema? can you show me some examples? i'm making here an xml reader.. thank you
17
by: wswilson | last post by:
In python, I could write: a = 1 if a in : do something... In c (and many other languages):
1
by: sarankarthik | last post by:
Hi, I have some array of values,say for example Attribute1 contains 1,2,3,4,5,6,7 values.. Please tell me how can i store multiple values in an xml file for a single variable. ...
1
by: Anil Verma | last post by:
How to compare a SQL variable against multiple values: Here is the scenario; Declare @JobTitle varchar(10) Select @JobTitle = JobTitle from tableName where xxx=xxx Now I want to compare...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.