【问题标题】:ASP.NET/VB Iterate Through Collection, Do..This on Result Found, Do..That on Result Not FoundASP.NET/VB 遍历集合,Do..This 对 Result Found,Do..That 对 Result Not Found
【发布时间】:2010-07-07 00:14:15
【问题描述】:
[这是一个简化的例子]
我有一个集合(“myCollection”),其中存在三个条目:(“hello”、“goodbye”、“welcome”)。我想遍历集合,如果集合中有“欢迎”条目,我想采取一项行动,如果该条目不存在,我想做其他事情。像这样(伪):
For Each entry in myCollection
If entry="welcome" Then
DoSomething()
End If
Next (If Not MsgBox("Bad!"))
建议?
【问题讨论】:
标签:
asp.net
vb.net
foreach
【解决方案1】:
试试这个:
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`
或者,LINQ 版本可能看起来更简洁:
If myCollection.Contains("welcome") Then
DoSomething()
Else
MsgBox("Bad!")
End If