Getting the array key in a 'foreach' loop

前端 未结 9 590
别跟我提以往
别跟我提以往 2021-02-03 22:42

How do I get the key of the current element in a foreach loop in C#?

For example:

PHP

foreach ($array as $key => $value)
{
             


        
9条回答
  •  再見小時候
    2021-02-03 23:34

    I answered this in another version of this question:

    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.

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

提交回复
热议问题