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

The LINQ’s Select() method projects each element of a sequence into a new form by incorporating the element’s index. The first argument to selector represents the element to process, and the second argument represents the 0-based index of that element in the source sequence.

 
The following code example demonstrates using the Select() method to find each element’s index.

Download  Run Code

 
Alternatively, we can avoid heap allocations using the following alternative syntax using ValueTuple starting with C#7:

Download  Run Code

 
The following example uses type inference when deconstructing the list of 2-tuples returned by the Select() method. Now we can directly access the index and the value fields inside the loop.

Download  Run Code

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