开发者

vb.net: index number in "for each"

Sometime in VB.net i have someth开发者_Python百科ing 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?


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


I believe your original way of doing it with a counter variable is the most efficient way of doing it. Using Linq or IndexOf would kill the performance.

Dim i as Integer = 0
For Each obj In myList
    'Do stuff
    i+=1
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.


If you need the index, change the way you iterate through the collection:

You have already come up with the simplest answer:

For i = 0 To Collection.Count() - 1
   DoStuffWith(Collection(i))
Next
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜