ASP.NET/VB Iterate Through Collection, Do..This on Result Found, Do..That on Result Not Found
[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?
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
精彩评论