How do you get the index of the current iteration of a foreach loop?

后端 未结 30 1718
刺人心
刺人心 2020-11-22 07:05

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 iter

30条回答
  •  醉酒成梦
    2020-11-22 07:17

    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.

    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.

提交回复
热议问题