test for variable not in a list of values

  • Thread starter Thread starter Keith G Hicks
  • Start date Start date
K

Keith G Hicks

How can I do this in vb.net?

Dim SomeVar as String = "red"

IF SomeVar NOT IN ("yellow", "green", "blue") THEN...
 
All I could find from my research is that with all the myriad of string
operators there are in vb.net this is not as simple as just a function. I'm
really surprised. I figured on something like this:

If CompareMany(SomeVar, "yellow", "green", "blue", "orange", "pink")

where the 1st param is the value that may or may not exist in the list that
follows and the list can contain any number of values. I used such a
function once in Delphi I think. Can't remember for sure which language.

Anyway, I ended up usign a case statement. Works fine but not as elegant as
I'd like.
 
Keith said:
How can I do this in vb.net?

Dim SomeVar as String = "red"

IF SomeVar NOT IN ("yellow", "green", "blue") THEN...


dim myItems as string()={"yellow", "green", "blue"}

if not myitems.contains("red") then

end if

I'd create the array once only.
 
Yeah, I like that Armin. Thanks.

I presume you meant this instead (parens on myItems instead of on string):

dim myItems() as string = {"yellow", "green", "blue"}
 
Keith said:
Yeah, I like that Armin. Thanks.

I presume you meant this instead (parens on myItems instead of on string):

dim myItems() as string = {"yellow", "green", "blue"}

Yes, this also works. I prefer my version because the _whole_ type
("string-array") is following the "As" keyword.
 
Keith,

You can easily write a function, similar to the following:

Public Function IsIn(Of T)(value As T, ParamArray values As T()) As Boolean
Return Array.IndexOf(values, value) <> -1
End Function

This way you can compare other types, not just string with a very compact
syntax
 
Back
Top