你如何获得一个foreach循环的当前迭代的指数? [英] How do you get the index of the current iteration of a foreach loop?

查看:129
本文介绍了你如何获得一个foreach循环的当前迭代的指数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一些罕见的语言结构,我没有遇到(如一些我最近了解到,一些对堆栈溢出)在C#中获得一个价值重估presenting foreach循环的当前迭代?

比如说,我现在做这样的事情视情况而定:

  INT I = 0;
的foreach(在收集对象o)
{
    // ...
    我++;
}


解决方案

的foreach 是遍历实现集合<一个href=\"http://msdn.microsoft.com/en-us/library/9eekhta0%28v=vs.110%29.aspx\"><$c$c>IEnumerable.它通过调用<一个做到这一点href=\"http://msdn.microsoft.com/en-us/library/s793z9y2%28v=vs.110%29.aspx\"><$c$c>GetEnumerator在集合,它会返回一个<一个href=\"http://msdn.microsoft.com/en-us/library/78dfe2yb%28v=vs.110%29.aspx\"><$c$c>Enumerator.

这枚举有一个方法和属性:


  • 的MoveNext()

  • 电流

当前返回枚举器是目前在对象,的MoveNext 更新电流来的下一个对象。

显然,索引的概念是外枚举​​的概念,并不能进行。

由于这一点,多数藏品都能够使用索引和循环结构被穿越。

我使用了在这种情况下循环相比具有局部变量跟踪指数大大preFER

Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?

For instance, I currently do something like this depending on the circumstances:

int i=0;
foreach (Object o in collection)
{
    // ...
    i++;
}

解决方案

The foreach is for iterating over collections that implement IEnumerable. It does this by calling GetEnumerator on the collection, which will return an Enumerator.

This Enumerator has a method and a property:

  • MoveNext()
  • Current

Current returns the object that Enumerator is currently on, MoveNext updates Current to the next object.

Obviously, the concept of an index is foreign to the concept of enumeration, and cannot be done.

Because of that, most collections are able to be traversed using an indexer and the for loop construct.

I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.

这篇关于你如何获得一个foreach循环的当前迭代的指数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆