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++;
}
The leading answer states:
"Obviously, the concept of an index is foreign to the concept of enumeration, and cannot be done."
While this is true of the current C# version, this is not a conceptual limit.
The creation of a new C# language feature by MS could solve this, along with support for a new Interface IIndexedEnumerable
If foreach is passed an IEnumerable and can't resolve an IIndexedEnumerable, but it is asked with var index, then the C# compiler can wrap the source with an IndexedEnumerable object, which adds in the code for tracking the index.
Why:
While most people here are not MS, this is a correct answer, and you can lobby MS to add such a feature. You could already build your own iterator with an extension function and use tuples, but MS could sprinkle the syntactic sugar to avoid the extension function
Using LINQ, C# 7, and the
System.ValueTuple
NuGet package, you can do this:You can use the regular
foreach
construct and be able to access the value and index directly, not as a member of an object, and keeps both fields only in the scope of the loop. For these reasons, I believe this is the best solution if you are able to use C# 7 andSystem.ValueTuple
.Here's a solution I just came up with for this problem
Original code:
Updated code
Extension Method:
C# 7 finally gives us an elegant way to do this:
You can write your loop like this:
After adding the following struct and extension method.
The struct and extension method encapsulate Enumerable.Select functionality.
Unless your collection can return the index of the object via some method, the only way is to use a counter like in your example.
However, when working with indexes, the only reasonable answer to the problem is to use a for loop. Anything else introduces code complexity, not to mention time and space complexity.