Using foreach with Index in C#
The foreach in C# allows you to iterate over a collection and also have access to the index of the current item. This can be very useful in many scenarios, such as when you need to update a specific item in a list or array, or when you need to perform some calculation based on the index of the current item, or you may want to print out the index of each item as you iterate over it. The syntax for using foreach with an index in C# is as follows:
{
// instructions
}
Here, each element of the collection is projected into an anonymous type using the Select method, which has both the element’s value and index.
Example
Here is an example where we have an array of strings, and we want to iterate over it using foreach and keep track of the index of each string:
using System.Linq;
class Program
{
static void Main(string[] args)
{
string[] colors = { "Red", "Green", "Blue" };
foreach(var item in colors.Select((Value, Index) => new { Value, Index }))
{
Console.WriteLine($"Item at index {item.Index}: {item.Value}");
}
}
}
Here, we first declare an array of strings called colors. We then use foreach with an index to iterate over the colors array, and for each string in the array, we print out its value along with its index using the Console.WriteLine method.
Conclusion
In this article, we discussed how to use foreach with index in C#, including its syntax and a full code example. When we need to maintain track of the current iteration number, utilizing foreach with an index can be a helpful trick.