3

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 ...

3 Answers3

4

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)
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • ah okay, yeah that's what i figured. just wanted to make sure! thanks! –  May 14 '13 at 12:32
1

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)

Community
  • 1
  • 1
Xaqron
  • 29,931
  • 42
  • 140
  • 205
0

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).

Kratz
  • 4,280
  • 3
  • 32
  • 55