Tag Archives: Developer

How do you get the index of the current iteration of a foreach loop?

Is there some rare language construct you haven’t encountered (like the few You have learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?

For instance, when you currently do something like this depending on the circumstances:

int i = 0;
foreach (Object o in collection)
{
    // ...
    i++;
}

foreach casting retrieval is generally not going to me more optimized than just using index-based access on a collection, though in many cases it will be equal. The purpose of foreach is to make your code readable, but it (usually) adds a layer of indirection, which isn’t free.

You could wrap the original enumerator with another that does contain the index information like code bellow:

foreach (var item in ForEachHelper.WithIndex(collection))
{
    Console.Write("Index=" + item.Index);
    Console.Write(";Value= " + item.Value);
    Console.Write(";IsLast=" + item.IsLast);
    Console.WriteLine();
}

Here is the code for the ForEachHelper class.

public static class ForEachHelper
{
    public sealed class Item<T>
    {
        public int Index { get; set; }
        public T Value { get; set; }
        public bool IsLast { get; set; }
    }

    public static IEnumerable<Item<T>> WithIndex<T>(IEnumerable<T> enumerable)
    {
        Item<T> item = null;
        foreach (T value in enumerable)
        {
            Item<T> next = new Item<T>();
            next.Index = 0;
            next.Value = value;
            next.IsLast = false;
            if (item != null)
            {
                next.Index = item.Index + 1;
                yield return item;
            }
            item = next;
        }
        if (item != null)
        {
            item.IsLast = true;
            yield return item;
        }            
    }
}

Or you can use this code:

int i = 0;
foreach (var item in Collection)
{
    item.index = i;
    ++i;
}