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++;
}
Using @FlySwat's answer, I came up with this solution:
You get the enumerator using
GetEnumerator
and then you loop using afor
loop. However, the trick is to make the loop's conditionlistEnumerator.MoveNext() == true
.Since the
MoveNext
method of an enumerator returns true if there is a next element and it can be accessed, making that the loop condition makes the loop stop when we run out of elements to iterate over.My solution for this problem is an extension method
WithIndex()
,http://code.google.com/p/ub-dotnet-utilities/source/browse/trunk/Src/Utilities/Extensions/EnumerableExtensions.cs
Use it like
Literal Answer -- warning, performance may not be as good as just using an
int
to track the index. At least it is better than usingIndexOf
.You just need to use the indexing overload of Select to wrap each item in the collection with an anonymous object that knows the index. This can be done against anything that implements IEnumerable.
You could wrap the original enumerator with another that does contain the index information.
Here is the code for the
ForEachHelper
class.How about something like this? Note that myDelimitedString may be null if myEnumerable is empty.
Could do something like this: