tags:

views:

575

answers:

5

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

+1  A: 

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.

Andrew Hare
Does anyone know why this is the case?
vg1890
+1  A: 

You would have to do it yourself. Mostly, if you're doing For Each (foreach in C#), then you don't care about iteration count.

John Saunders
A: 

Foreach loops for each element M it finds in a collection of M elements.

So, no, there is no explicit iteration count as there would be in a FOR loop.

Matthew Jones
+2  A: 

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
JaredPar
+1  A: 

If I need a 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.

SchlaWiener