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

后端 未结 30 2270
刺人心
刺人心 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:19

    Literal Answer -- warning, performance may not be as good as just using an int to track the index. At least it is better than using IndexOf.

    You just need to use the indexing overload of Select to wrap each item in the collection with an anonymous object that knows the index. This can be done against anything that implements IEnumerable.

    System.Collections.IEnumerable collection = Enumerable.Range(100, 10);
    
    foreach (var o in collection.OfType().Select((x, i) => new {x, i}))
    {
        Console.WriteLine("{0} {1}", o.i, o.x);
    }
    
        

    提交回复
    热议问题