Earn income with your C# skills
Sign up and we'll send you the best freelance opportunities straight to your inbox.
We're building the largest self-service freelancing marketplace for people like you.

How to get the index of the current iteration in a foreach loop.

Using an index variable.

Create an index variable and initialize it to 0. Then increment its value with each iteration.


using System;
using System.Collections.Generic;

public class IndexOfIteration
{
    public static void Main()
    {
        var numbers = new List<int>() { 1, 2, 3, 4, 8, 10 };
        int index = 0;
        
        foreach (var number in numbers)
        {
            Console.WriteLine($"Index: {index}. Value: {number}");
            index++;
        }
    }
}


Using LINQ Select().

With Select() create a list of values paired with index values. Then use the index while running the foreach loop.


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

public class IndexOfIteration
{
    public static void Main()
    {
        var numbers = new List<int>() { 1, 2, 3, 4, 8, 10 };

        var items = numbers.Select((value, index) => new { value, index });

        foreach (var item in items)
        {
            Console.WriteLine($"Index: {item.Index}. Value: {item.Value}");
        }
    }
}



Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Licensing       EULA       Sitemap      
© Data & Object Factory, LLC.
Made with    in Austin, Texas.      Vsn 1.3.0