To start with I\'ll say that I agree that goto statements are largely made irrelevant by higher level constructs in modern programming languages and shouldn\'t be used when
Personally I like Mark Byer's option, but you could always write your own generic method for this:
public static void IterateWithSpecialFirst(this IEnumerable source,
Action firstAction,
Action subsequentActions)
{
using (IEnumerator iterator = source.GetEnumerator())
{
if (iterator.MoveNext())
{
firstAction(iterator.Current);
}
while (iterator.MoveNext())
{
subsequentActions(iterator.Current);
}
}
}
That's relatively straightforward... giving a special last action is slightly harder:
public static void IterateWithSpecialLast(this IEnumerable source,
Action allButLastAction,
Action lastAction)
{
using (IEnumerator iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
{
return;
}
T previous = iterator.Current;
while (iterator.MoveNext())
{
allButLastAction(previous);
previous = iterator.Current;
}
lastAction(previous);
}
}
EDIT: As your comment was concerned with the performance of this, I'll reiterate my comment in this answer: while this general problem is reasonably common, it's not common for it to be such a performance bottleneck that it's worth micro-optimizing around. Indeed, I can't remember ever coming across a situation where the looping machinery became a bottleneck. I'm sure it happens, but that isn't "common". If I ever run into it, I'll special-case that particular code, and the best solution will depend on exactly what the code needs to do.
In general, however, I value readability and reusability much more than micro-optimization.