开发者

ASP.NET/VB Iterate Through Collection, Do..This on Result Found, Do..That on Result Not Found

开发者 https://www.devze.com 2023-01-06 03:15 出处:网络
[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 coll

[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
0

精彩评论

暂无评论...
验证码 换一张
取 消