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++;
}
I just had this problem, but thinking around the problem in my case gave the best solution, unrelated to the expected solution.
It could be quite a common case, basically, I'm reading from one source list and creating objects based on them in a destination list, however, I have to check whether the source items are valid first and want to return the row of any error. At first-glance, I want to get the index into the enumerator of the object at the Current property, however, as I am copying these elements, I implicitly know the current index anyway from the current destination. Obviously it depends on your destination object, but for me it was a List, and most likely it will implement ICollection.
i.e.
Not always applicable, but often enough to be worth mentioning, I think.
Anyway, the point being that sometimes there is a non-obvious solution already in the logic you have...
I don't think this should be quite efficient, but it works:
Why foreach ?!
The simplest way is using for instead of foreach if you are using List .
OR if you want use foreach :
you can use this to khow index of each Loop :
Better to use keyword
continue
safe construction like thisThis is how I do it, which is nice for its simplicity/brevity, but if you're doing a lot in the loop body
obj.Value
, it is going to get old pretty fast.The
foreach
is for iterating over collections that implementIEnumerable
. It does this by callingGetEnumerator
on the collection, which will return anEnumerator
.This Enumerator has a method and a property:
Current
returns the object that Enumerator is currently on,MoveNext
updatesCurrent
to the next object.Obviously, the concept of an index is foreign to the concept of enumeration, and cannot be done.
Because of that, most collections are able to be traversed using an indexer and the for loop construct.
I greatly prefer using a for loop in this situation compared to tracking the index with a local variable.