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

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

    C# 7 finally gives us an elegant way to do this:

    static class Extensions
    {
        public static IEnumerable<(int, T)> Enumerate(
            this IEnumerable input,
            int start = 0
        )
        {
            int i = start;
            foreach (var t in input)
            {
                yield return (i++, t);
            }
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var s = new string[]
            {
                "Alpha",
                "Bravo",
                "Charlie",
                "Delta"
            };
    
            foreach (var (i, t) in s.Enumerate())
            {
                Console.WriteLine($"{i}: {t}");
            }
        }
    }
    

提交回复
热议问题