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

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

    Finally C#7 has a decent syntax for getting an index inside of a foreach loop (i. e. tuples):

    foreach (var (item, index) in collection.WithIndex())
    {
        Debug.WriteLine($"{index}: {item}");
    }
    

    A little extension method would be needed:

    public static IEnumerable<(T item, int index)> WithIndex(this IEnumerable self)       
       => self.Select((item, index) => (item, index)); 
    

提交回复
热议问题