Dofactory.com
Dofactory.com

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}");
        }
    }
}


Jack Poorte
Jack Poorte
Last updated on Sep 30, 2023



Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Cookies       Do Not Sell       Licensing      
Made with    in Austin, Texas.  - vsn 44.0.0
© Data & Object Factory, LLC.