views:

272

answers:

2

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  A: 

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
magnifico
Wouldnt this be of pretty low performance? It have to seek the whole Collection to get the Index.
bortao
I have no idea what the performance is. If you are mostly interested in performance, you should update your question to reflect that.
magnifico
ok.. no need to be rude. just wondering :)
bortao
Sorry if I came off as rude, that wasn't my intention. :)
magnifico
+1  A: 

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.

Ahmad Mageed