Does a For Each
loop in Visual Basic have an iteration count, or would I have to do that myself?
It repeats the enclosed block of statements while a Boolean condition is True or until the condition becomes True. It could be terminated at any time with the Exit Do statement. It repeats a group of statements a specified number of times and a loop index counts the number of loop iterations as the loop executes.
A for... next loop executes a set of statements for successive values of a variable until a limiting value is encountered. Such values are specified by establishing an initial value (num. exp1), a limiting value (num. exp2), and an optional increment value (num.
To begin, we see a simple For-loop that starts at 0, and continues to 2 (it includes 2, which is specified as the loop bound). Tip In VB.NET the top bound is inclusive. So this loop is like an "i <= 2" loop bound in C# or similar languages.
In Visual Basic, using the Exit keyword, we can stop the execution of the For loop statement based on our requirements. Following is the example of stopping the execution of For loop using Exit statement.
Unfortunately you have to do that yourself. The For Each
construct uses an implementation the IEnumerator
interface to iterate a sequence and the IEnumerator
interface does not expose any members to indicate its position or current index within the sequence.
If I need an iterator variable, I use a for
loop instead (every IEnumerable should have a .Count property).
Instead of
For Each element as MyType in MyList
....
Next
write
For i as integer = 0 to MyList.Count - 1
element = MyList(i)
....
Next
which will be the same result. You have i
as an iterator and element
holds the current element.
If you are using Visual Studio 2009 (or VB.Net 9.0), you can use a Select override to get a count with the values.
For Each cur in col.Select(Function(x,i) New With { .Index = i, .Value = x })
...
Next
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With