vb.net:“for each”中的索引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2331132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
vb.net: index number in "for each"
提问by ariel
Sometime in VB.net i have something like:
有时在 VB.net 我有类似的东西:
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?
还有其他获取索引的方法吗?
回答by Jim Counts
If you are using a generic collection (Collection(of T)) then you can use the IndexOf method.
如果您使用的是泛型集合(Collection(of T)),那么您可以使用IndexOf 方法。
For Each El in Collection
Write(Collection.IndexOf(El) & " = " & El)
Next
回答by Mark Entingh
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.
我相信您使用计数器变量的原始方法是最有效的方法。使用 Linq 或 IndexOf 会降低性能。
Dim i as Integer = 0
For Each obj In myList
'Do stuff
i+=1
Next
回答by Ahmad Mageed
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.
如果您需要索引,那么 for 循环是最直接的选择并且具有出色的性能。除了您提到的替代方法外,您还可以使用重载Select
方法来跟踪索引并继续使用 foreach 循环。
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.
但是,如果唯一的原因是迭代它并知道索引,我会坚持使用 for 循环。上面没有说清楚你为什么选择跳过 for 循环。