Reputation: 13769
Does a For Each
loop in Visual Basic have an iteration count, or would I have to do that myself?
Upvotes: 11
Views: 18834
Reputation: 31723
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.
Upvotes: 8
Reputation: 754715
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
Upvotes: 7
Reputation: 26190
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.
Upvotes: 0
Reputation: 161773
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.
Upvotes: 2
Reputation: 351516
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.
Upvotes: 9