C# .Net indexed foreach

A quick demo on how to use an indexed foreach in C#.

using System;
using System.Linq;

namespace CsharpIndexedForeachDemo
{
    class CsharpIndexedForeachExample
    {
        static void Main()
        {
            // Create a range of integers
            var myRange = Enumerable.Range(0, 100);

            // Iterate over range
            foreach (var i in myRange.Select((x, i) => new { Value = x, Index = i}))
            {
                Console.WriteLine(i.Index);
                // Break on 10 results
                if (i.Index >= 10)
                    break;
            }
            Console.ReadKey();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *