C# foreach and index

Content:

(saw something on LinkedIn)

I guess everybody knows the issue: you want to use the nice foreach, but you need the index, so you fallback to old ugly C style for.

Turn out .NET 9 introduced a little gem. Demo:

using System;
using System.Collections.Generic;
using System.Linq;

namespace IxFun
{
    public class Program
    {
        public static void Main(string[] args)
        {
            IList<string> slst = new List<string> { "A", "B", "C" };
            foreach(string s in slst)
            {
                Console.WriteLine(s);
            }
            for(int i = 0; i < slst.Count; i++)
            {
                Console.WriteLine("{0} : {1}", i, slst[i]);
            }
            foreach(var (i,s) in slst.Index())
            {
                Console.WriteLine("{0} : {1}", i, s);
            }
        }
    }
}

Comments: