(C#) Get index of current foreach iteration
Posted
by Graphain
on Stack Overflow
See other posts from Stack Overflow
or by Graphain
Published on 2008-09-04T01:38:39Z
Indexed on
2010/03/26
15:33 UTC
Read the original article
Hit count: 425
c#
Hi,
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++;
}
Answers:
@bryansh: I am setting the class of an element in a view page based on the position in the list. I guess I could add a method that gets the CSSClass for the Objects I am iterating through but that almost feels like a violation of the interface of that class.
@Brad Wilson: I really like that - I've often thought about something like that when using the ternary operator but never really given it enough thought.
As a bit of food for thought it would be nice if you could do something similar to somehow add (generically to all IEnumerable objects) a handle on the enumerator to increment the value that an extension method returns i.e. inject a method into the IEnumerable interface that returns an iterationindex.
Of course this would be blatant hacks and witchcraft... Cool though...
@crucible: Awesome I totally forgot to check the LINQ methods. Hmm appears to be a terrible library implementation though. I don't see why people are downvoting you though. You'd expect the method to either use some sort of HashTable of indices or even another SQL call, not an O(N) iteration... (@Jonathan Holland yes you are right, expecting SQL was wrong)
@Joseph Daigle: The difficulty is that I assume the foreach casting/retrieval is optimised more than my own code would be.
@Jonathan Holland: Ah, cheers for explaining how it works and ha at firing someone for using it.
© Stack Overflow or respective owner