Check whether a string is inside a number of strings

J

Jan

Hi,

Is there any elegant way in VB.NET to check whether a certain string is part
of a "collection" of strings.

Something like IF "teststring" in {"string1", "string2", "string3",
"teststring"} THEN

Thanks,
Jan
 
E

EricJ

have a look at the arraylist class
that has a search and boolean search
copy your array to an arraylist, (sort it and do a boolean search), search
it

eric
 
C

Cor

Hi Jan,

I did wish there was an indexofany(string())

That is as far as I know not, but maybe you can do it with something like
this,
I did made some more in this sample than you asked, so it can shorter.

\\\\
Dim mytestvalues() As String = {"Jan", "funny", "string3"}
For i As Integer = 0 To mytestvalues.Length
Dim y As Integer = _
"This is a FunnyString Approach".ToLower.IndexOf(mytestvalues(i))
If y <> -1 Then
MessageBox.Show("It is " & mytestvalues(i) & _
" on postition " & y.ToString)
Exit For
End If
Next
///
That string is normaly of course
dim x as string = "This is a FunnyString Approach" and then
y = x.ToLower.IndexOf(mytestvalues(i))

I hope this helps a little bit?

Cor
 
J

Jan

Cor,

Looks like IndexOf is a step in the right direction :

IF ",string1,string2,string3,teststring,".indexof("," & "teststring" & ",")
<> 1 THEN ....

- should work provided teststring does not contain any ","
- is short
- but is not so elegant ....

Anything more elegant ?

Thanks,
Jan
 
H

Herfried K. Wagner [MVP]

* "Jan said:
Is there any elegant way in VB.NET to check whether a certain string is part
of a "collection" of strings.

Something like IF "teststring" in {"string1", "string2", "string3",
"teststring"} THEN

An elegant way is IMO a loop ('For...To') in which you compare the
strings to the string. Notice that this may have bad performance if
there are many strings. Using, for example, binary search in a sorted
list of strings or special tree structures may be faster.
 
J

Jan

Cor,

Perfect !

So it becomes :

dim asPossibleValues() as string = {"test1", "test2", "test3"}
if Array.IndexOf(asPossibleValues,"test3") <> -1 then
.......

- works well
- concise
- elegant

Thanks a lot,
Jan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top