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

Matt Mitchell picture Matt Mitchell · Sep 4, 2008 · Viewed 986.6k times · Source

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

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

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

Answer

bcahill picture bcahill · Jul 11, 2012

Ian Mercer posted a similar solution as this on Phil Haack's blog:

foreach (var item in Model.Select((value, i) => new { i, value }))
{
    var value = item.value;
    var index = item.i;
}

This gets you the item (item.value) and its index (item.i) by using this overload of LINQ's Select:

the second parameter of the function [inside Select] represents the index of the source element.

The new { i, value } is creating a new anonymous object.

Heap allocations can be avoided by using ValueTuple if you're using C# 7.0 or later:

foreach (var item in Model.Select((value, i) => ( value, i )))
{
    var value = item.value;
    var index = item.i;
}

You can also eliminate the item. by using automatic destructuring:

<ol>
foreach ((MyType value, Int32 i) in Model.Select((value, i) => ( value, i )))
{
    <li id="item_@i">@value</li>
}
</ol>