vb.net:“foreach”中的索引号
有时在 VB.net 中我有类似的情况:
For Each El in Collection
Write(El)
Next
但如果我需要索引号,我必须将其更改为
For I = 0 To Collection.Count() - 1
Write(I & " = " & Collection(I))
Next
甚至(更糟糕)
I = 0
For Each El In Collection
Write(I & " = " & El)
I += 1
Next
是否还有另一种获取索引的方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用的是通用集合(Collection(of T)),那么您可以使用 IndexOf 方法。
If you are using a generic collection (Collection(of T)) then you can use the IndexOf method.
我相信您使用计数器变量的原始方法是最有效的方法。使用 Linq 或 IndexOf 会降低性能。
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.
如果您需要索引,那么 for 循环是最直接的选择,并且具有出色的性能。除了您提到的替代方案之外,您还可以使用重载的
Select
方法来跟踪索引并继续使用 foreach 循环。
但是,如果唯一的原因是迭代它并知道索引,我会坚持使用 for 循环。上面并没有说明为什么你选择跳过 for 循环。
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.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: