This post will discuss how to get the current index of a foreach loop in C#.

There are several ways to get the index of the current iteration of a foreach loop. The foreach loop in C# doesn’t have a built-in index. You can maintain an explicit counter, starting with 0, and increment the counter by 1 in each iteration of the foreach loop. Here’s what the code would look like:

Download  Run Code

Output:

Element 2 present at index 0
Element 5 present at index 1
Element 1 present at index 2
Element 7 present at index 3

 
The following program creates an extension method for the above code.

Download  Run Code

 
Alternatively, you can use a standard for-loop to easily get the index for each element as follows:

Download  Run Code

 
The following solution creates an anonymous object for every element in the collection by using an overload of LINQ’s Select. The Value property stores the original value in the collection, and the Index property stores the index of each value within the collection.

Download  Run Code

 
Finally, you can avoid heap allocations by using the following alternative syntax using ValueTuple starting with C#7:

Download  Run Code

That’s all about getting the current index of a foreach loop in C#.