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