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

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.


    Ian Mercer posted a similar solution as this on Phil Haack's blog:

    foreach (var item in Model.Select((value, i) => new { i, value }))
    {
        var value = item.value;
        var index = item.i;
    }
    

    This gets you the item ( item.value ) and its index ( item.i ) by using this overload of Linq's Select :

    the second parameter of the function [inside Select] represents the index of the source element.

    The new { i, value } is creating a new anonymous object.


    可以做这样的事情:

    public static class ForEachExtensions
    {
        public static void ForEachWithIndex<T>(this IEnumerable<T> enumerable, Action<T, int> handler)
        {
            int idx = 0;
            foreach (T item in enumerable)
                handler(item, idx++);
        }
    }
    
    public class Example
    {
        public static void Main()
        {
            string[] values = new[] { "foo", "bar", "baz" };
    
            values.ForEachWithIndex((item, idx) => Console.WriteLine("{0}: {1}", idx, item));
        }
    }
    
    链接地址: http://www.djcxy.com/p/1522.html

    上一篇: IEnumerable <T>的foreach相当于LINQ

    下一篇: 你如何获得foreach循环的当前迭代的索引?