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++;
}
For interest, Phil Haack just wrote an example of this in the context of a Razor Templated Delegate (http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx)
Effectively he writes an extension method which wraps the iteration in an "IteratedItem" class (see below) allowing access to the index as well as the element during iteration.
However, while this would be fine in a non-Razor environment if you are doing a single operation (i.e. one that could be provided as a lambda) it's not going to be a solid replacement of the for/foreach syntax in non-Razor contexts.
If the collection is a list, you can use List.IndexOf, as in:
I wasn't sure what you were trying to do with the index information based on the question. However, in C#, you can usually adapt the IEnumerable.Select method to get the index out of whatever you want. For instance, I might use something like this for whether a value is odd or even.
This would give you a dictionary by name of whether the item was odd (1) or even (0) in the list.
I built this in LINQPad:
You could also just use
string.join
: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.Finally C#7 has a decent syntax for getting an index inside of a
foreach
loop (i. e. tuples):A little extension method would be needed: