views:

20

answers:

1

[This is a simplified example]

I have a collection ("myCollection") in which exists three entries: ("hello", "goodbye", "welcome"). I want to iterate through the collection and if in the collection there is the entry "welcome" I want to take one action, if that entry doesn't exist I want to do something else. Like this (pseudo):

For Each entry in myCollection
  If entry="welcome" Then
    DoSomething()
  End If
Next (If Not MsgBox("Bad!"))

Suggestions?

+3  A: 

Try this:

Dim found as Boolean = false
For Each entry in myCollection 
  If entry="welcome" Then 
    DoSomething() 
    found = True
    Exit For ' Assumes only want to DoSomething for one "welcome" '
  End If 
Next

If Not found Then
  MsgBox("Bad!")
End If `enter code here`

Alternatively the LINQ version may look more succinct:

If myCollection.Contains("welcome") Then
  DoSomething()
Else
  MsgBox("Bad!")
End If
Graphain