Results 1 to 1 of 1

Thread: NET9 Enumerable.Index<T>

  1. #1

    Thread Starter
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,708

    NET9 Enumerable.Index<T>

    Enumerable.Index<T> returns an enumerable that incorporates the element's index into a tuple.
    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();
    }
    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)
        {
            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();
    }
    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:
    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);
        }
    }
    Last edited by kareninstructor; Dec 23rd, 2024 at 12:45 PM. Reason: Modified last sample

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width