Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'For Each' VB.NET iteration count

Tags:

vb.net

Does a For Each loop in Visual Basic have an iteration count, or would I have to do that myself?

like image 249
Steven Avatar asked Jun 18 '09 20:06

Steven


People also ask

How are loops executed in VB?

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.

What is a for next loop?

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.

Is VB For loop inclusive?

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.

How do you end a loop in Visual Basic?

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.


3 Answers

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.

like image 69
Andrew Hare Avatar answered Sep 21 '22 20:09

Andrew Hare


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.

like image 25
Jürgen Steinblock Avatar answered Sep 18 '22 20:09

Jürgen Steinblock


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
like image 32
JaredPar Avatar answered Sep 18 '22 20:09

JaredPar