tags:

views:

249

answers:

5

Is it possible to have something similar to an SQL 'WHERE' clause in a For Each loop in VB.NET? I.E.

 FOR EACH event IN events 
    'WHERE eventdate=getdate
 NEXT
A: 

You can't do what you're describing in a for each loop. You can do it in a for loop in C#, but I don't think you can in VB .NET.

You really have multiple options about resolving this.

One way would be to do this:

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

You can also do it using LINQ, but it's arguable in this case if that would help you.

Joseph
A: 

Sure it is, this example should be enough to get you going:

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

      ' Do something here 
Next
JBrooks
+2  A: 

in LINQ it would be (.NET 3.5 or higher)

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

And Non-Linq (.Net 2.0 or lower)

For Each event in events
   If event.eventdate = getdate Then
      'Process event
   End If
Next
Paully
+1  A: 

With 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
Stefan
+1, that's the answer I would've given. No need for the "Select pers" at the end, though.
Jakob Gade
Jakob, I wasnt sure I could omitt the "select pers" at the end and couldnt test it before posting, but have edited the answer now. Thanks for the point!
Stefan
+1  A: 

My 2 cents:

If you are using VB 8.0 (.NET Framework 2.0) with List(Of T).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

Alfred Myers