vb.net For Each 循环迭代计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16530391/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:34:42  来源:igfitidea点击:

For Each Loop Iteration Count

vb.netforeachiteration

提问by Tim Schmelter

Can we keep track of our iterationin our loop when we use a For Each? I like to use the For Each loops for looping through my objects but I cannot seem to find a way to keep an index of where I'm at in the loop. Unless of course I create my own ...

当我们使用For Each时,我们可以在循环中跟踪我们的迭代吗?我喜欢使用 For Each 循环来循环遍历我的对象,但我似乎无法找到一种方法来保留我在循环中所处位置的索引。当然,除非我创建自己的......

回答by Tim Schmelter

If you want to have an index, use a For-loop instead of a For each. That's why it exists.

如果您想拥有索引,请使用For-loop 而不是For each。这就是它存在的原因。

For i As Int32 = 0 To objects.Count - 1
    Dim obj = objects(i)
Next

Of course nothing prevents you from creating your own counter:

当然,没有什么可以阻止您创建自己的计数器:

Dim counter As Int32 = 0
For Each obj In objects
    counter += 1
Next

or you can use Linq:

或者你可以使用 Linq:

Dim query = objects.Select(Function(obj, index) "Index is:" & index)

回答by Xaqron

There's no built-in solution yet. Of course you know how to do it with a counter but thismaybe what you are looking for (By Jon Skeet)

目前还没有内置的解决方案。当然,你知道如何与反做,但这样也许你在找什么(通过乔恩斯基特

回答by Kratz

You can do it like this:

你可以这样做:

 Dim index as integer = 0
 For Each item in list
      'do stuff
      index += 1
 Next

Off course, depending on the collection your iterating over, there is no guaranteeing that itemwill be the same as list.item(index), but wether or not that matters depends on what you are doing.

当然,根据您迭代的集合,不能保证item与 相同list.item(index),但这是否重要取决于您在做什么。

For index as integer = 0 to list.count - 1
     Dim item = list.item(index)
     'do stuff
Next

That is the other alternative if you need itemto be the same as list.item(index).

如果您需要itemlist.item(index).