Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action(Of T) in Visual Basic in List(Of T).ForEach

I have searched high and low for documentation on how to use this feature. While the loop I could write would be simple and take no time, I really would like to learn how to use this.

Basically I have a class, say, Widget, with a Save() sub that returns nothing. So:

Dim w as New Widget()
w.Save()

basically saves the widget. Now let's say I have a generic collection List(Of Widget) name widgetList(Of Widget) and I want to run a Save() on each item in that list. It says I can do a

widgetList.ForEach([enter Action(Of T) here])

....but how in the F does this work??? There is no documentation anywhere on the intrablags. Help would be much much appreciated.

like image 276
Jason Avatar asked May 21 '09 09:05

Jason


People also ask

What is an action in Visual Basic?

In visual basic, Action is a built-in generic delegate same as Func delegate to hold the reference of one or more methods but the only difference is the Action delegate will not return any value.

How to Exit For Each loop vb?

The Exit For statement causes execution to exit the For … Next loop and transfers control to the statement that follows the Next statement. The Continue For statement transfers control immediately to the next iteration of the loop.

Will you use a For Each loop or just a simple For loop?

Only use the for-each loop when you want to loop through all the values in an array or list. If you only want to loop through part of an array or list use a for loop instead. Also use a for loop instead of a for-each loop if you want to change any of the values in the array or list.


1 Answers

well, I'm really outdated now... :-) but in VB it's:

widgetList.ForEach(Sub(w) w.Save())

or, more complicated:

widgetList.ForEach(New Action(Of Widged)(Sub(w As Widged) w.Save()))
like image 167
Sebastian Avatar answered Sep 30 '22 13:09

Sebastian