Find current index in a foreach loop in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 3, 2, 5, 6, 4, 8 }; foreach (var item in nums.Select((value, index) => new { value, index })) { Console.WriteLine("Element {1} present at index {0}", item.index, item.value); } } } /* Output: Element 3 present at index 0 Element 2 present at index 1 Element 5 present at index 2 Element 6 present at index 3 Element 4 present at index 4 Element 8 present at index 5 */ |
Alternatively, we can avoid heap allocations using the following alternative syntax using ValueTuple starting with C#7:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 3, 2, 5, 6, 4, 8, 7 }; foreach (var item in nums.Select((value, index) => (value, index))) { Console.WriteLine("Element {1} present at index {0}", item.index, item.value); } } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 3, 2, 5, 6, 4, 8, 7 }; foreach (var (value, index) in nums.Select((value, index) => (value, index))) { Console.WriteLine("Element {1} present at index {0}", index, value); } } } |
That’s all about finding the current index in a foreach loop in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)