在VB.NET中模拟For Each循环中的'Where'子句

时间:2009-08-20 00:16:26

标签: vb.net

是否有可能在VB.NET中的For Each循环中有类似于SQL'WHERE'子句的内容? 即。

 FOR EACH event IN events 
    'WHERE eventdate=getdate
 NEXT

5 个答案:

答案 0 :(得分:6)

LINQ中的

(.NET 3.5或更高版本)

For Each event in events.Where(Function(x) x.eventdate = getdate)
      'Process event
Next

非Linq(.Net 2.0或更低版本)

For Each event in events
   If event.eventdate = getdate Then
      'Process event
   End If
Next

答案 1 :(得分:2)

使用LINQ:

For Each p As Person In (From pers In Persons Where pers.Firstname = "Stefan")
            'Only handle persons with first name "Stefan"
            MsgBox(p.LastName)
        Next
    End Sub

答案 2 :(得分:1)

我的2美分:

如果您使用带有List(Of T)的VB 8.0(.NET Framework 2.0).FindAll:


Public Shared Sub Show()
    Dim filtredEvents As List(Of Event) = New List(Of Event)().FindAll(Function (ByVal e As Event) 
        Return (e.EventDate = DateTime.Today)
    End Function)
    Dim anEvent As Event
    For Each anEvent In filtredEvents
        Console.WriteLine(anEvent.EventDate)
    Next
End Sub

答案 3 :(得分:0)

你无法在每个循环中执行你所描述的内容。你可以在C#的for循环中完成它,但我不认为你可以在VB .NET中使用。

你真的有很多选择来解决这个问题。

一种方法是:

For Each event As Event in events
    If eventdate = getdate then
        Continue For
    End If
Next

你也可以使用LINQ来做到这一点,但在这种情况下,如果能帮助你的话,这是有争议的。

答案 4 :(得分:0)

当然可以,这个例子足以让你前进:

For Each dvr As DataRowView In dv
    If dvr("IsVisible") = False Then
        Continue For
    End If

      ' Do something here 
Next