user2379049
user2379049

Reputation:

For Each Loop Iteration Count

Can we keep track of our iteration in our loop when we use a For Each? I like to use the For Each loops for looping through my objects but I cannot seem to find a way to keep an index of where I'm at in the loop. Unless of course I create my own ...

Upvotes: 3

Views: 15838

Answers (3)

Xaqron
Xaqron

Reputation: 30847

There's no built-in solution yet. Of course you know how to do it with a counter but this maybe what you are looking for (By Jon Skeet)

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460108

If you want to have an index, use a For-loop instead of a For each. That's why it exists.

For i As Int32 = 0 To objects.Count - 1
    Dim obj = objects(i)
Next

Of course nothing prevents you from creating your own counter:

Dim counter As Int32 = 0
For Each obj In objects
    counter += 1
Next

or you can use Linq:

Dim query = objects.Select(Function(obj, index) "Index is:" & index)

Upvotes: 4

Kratz
Kratz

Reputation: 4330

You can do it like this:

 Dim index as integer = 0
 For Each item in list
      'do stuff
      index += 1
 Next

Off course, depending on the collection your iterating over, there is no guaranteeing that item will be the same as list.item(index), but wether or not that matters depends on what you are doing.

For index as integer = 0 to list.count - 1
     Dim item = list.item(index)
     'do stuff
Next

That is the other alternative if you need item to be the same as list.item(index).

Upvotes: 0

Related Questions