Enumerable.Index<T> returns an enumerable that incorporates the element's index into a tuple.
Some developers may not care for the above, then they might use.Code:using static System.Globalization.DateTimeFormatInfo; internal partial class Program { static void Main(string[] args) { foreach (var (month, index) in Months.Index()) { Console.WriteLine($"{index,-5}{month}"); } Console.ReadLine(); } public static List<string> Months => CurrentInfo.MonthNames[..^1].ToList(); }
For the developer targeting a .NET Core Framework prior to NET 9 the following is similar to NET 9 as per the first example.Code:using static System.Globalization.DateTimeFormatInfo; internal partial class Program { static void Main(string[] args) { var index = -1; foreach (var month in Months) { ++index; Console.WriteLine($"{index,-5}{month}"); } Console.ReadLine(); } public static List<string> Months => CurrentInfo.MonthNames[..^1].ToList(); }
Code:public static IEnumerable<(int Index, TSource Item)> Index<TSource>(this IEnumerable<TSource> source) { int index = -1; foreach (TSource element in source) { checked { index++; } yield return (index, element); } }




Reply With Quote
