c sharp

How to Use foreach with Index in C#

A typical C# loop structure for iterating across collections or arrays is the foreach loop. However, it does not provide an index counter by default, which can sometimes be useful in certain scenarios. In this article, we will discuss how to use foreach with index in C#, including its syntax and a full code example.

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:

foreach(var item in collection.Select((Value, Index) => new { Value, Index }))

{

  // 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;

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.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.