Often I have to code a loop that needs a special case for the first item, the code never seems as clear as it should ideally be.
Short of a redesign of the C# language,
How about:
using (var erator = enumerable.GetEnumerator())
{
if (erator.MoveNext())
{
ProcessFirst(erator.Current);
//ProcessOther(erator.Current); // Include if appropriate.
while (erator.MoveNext())
ProcessOther(erator.Current);
}
}
You could turn that into an extension if you want:
public static void Do(this IEnumerable source,
Action firstItemAction,
Action otherItemAction)
{
// null-checks omitted
using (var erator = source.GetEnumerator())
{
if (!erator.MoveNext())
return;
firstItemAction(erator.Current);
while (erator.MoveNext())
otherItemAction(erator.Current);
}
}