foreach with index

This question already has an answer here:

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

  • I keep this extension method around for this:

    public static void Each<T>( this IEnumerable<T> ie, Action<T, int> action )
    {
        var i = 0;
        foreach ( var e in ie ) action( e, i++ );
    }
    

    And use it like so:

    var strings = new List<string>();
    strings.Each( ( str, n ) =>
    {
        // hooray
    } );
    

    Or to allow for break -like behaviour:

    public static bool Each<T>( this IEnumerable<T> ie, Func<T, int, bool> action )
    {
        int i = 0;
        foreach ( T e in ie ) if( !action( e, i++ ) ) return false;
        return true;
    }
    
    var strings = new List<string>() { "a", "b", "c" };
    bool iteratedAll = strings.Each( (str, n) ) =>
    {
        if( str == "b" ) return false;
        return true;
    } );
    

    You can do the following

    foreach ( var it in someCollection.Select((x,i) => new { Value = x, Index=i }) )
    {
       if ( it.Index > SomeNumber) //      
    }
    

    This will create an anonymous type value for every entry in the collect. It will have two properties

  • Value: with the original value in the collection
  • Index: with the index within the collection

  • The C# foreach doesn't have a built in index. You'll need to add an integer outside the foreach loop and increment it each time.

    int i = -1;
    foreach (Widget w in widgets)
    {
       i++;
       // do something
    }
    

    Alternatively, you could use a standard for loop as follows:

    for (int i = 0; i < widgets.Length; i++)
    {
       w = widgets[i];
       // do something
    }
    
    链接地址: http://www.djcxy.com/p/52964.html

    上一篇: 从foreach循环获取当前索引

    下一篇: 带索引的foreach