Does a For-Each
loop in VB have an iteration count, or would I have to do that myself?
views:
575answers:
5Unfortunately 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.
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.
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.
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 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.