vb.net: index number in "for each"

Viewed 59754

Sometime in VB.net i have something like:

For Each El in Collection
   Write(El)
Next

But if i need the index number, i have to change it to

For I = 0 To Collection.Count() - 1
   Write(I & " = " & Collection(I))
Next

Or even (worse)

I = 0
For Each El In Collection
   Write(I & " = " & El)
   I += 1
Next

Is there another way of getting the index?

3 Answers

If you are using a generic collection (Collection(of T)) then you can use the IndexOf method.

For Each El in Collection
   Write(Collection.IndexOf(El) & " = " & El)
Next

If you need the index then a for loop is the most straightforward option and has great performance. Apart from the alternatives you mentioned, you could use the overloaded Select method to keep track of the indices and continue using the foreach loop.

Dim list = Enumerable.Range(1, 10).Reverse() ''# sample list
Dim query = list.Select(Function(item, index) _
                           New With { .Index = index, .Item = item })
For Each obj In query
    Console.WriteLine("Index: {0} -- Item: {1}", obj.Index, obj.Item)
Next

However, I would stick to the for loop if the only reason is to iterate over it and know the index. The above doesn't make it clear why you chose to skip the for loop.

Related