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++;
}
Best Solution
Ian Mercer posted a similar solution as this on Phil Haack's blog:
This gets you the item (
item.value
) and its index (item.i
) by using this overload of LINQ'sSelect
: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:You can also eliminate the
item.
by using automatic destructuring: