Neat way to write loop that has special logic for the first item in a collection
c#, collections
Solution
You could try:
collection.first(x=>
{
//...
}).rest(x=>
{
//...
}).run();
first / rest would look like:
FirstPart<T> first<T>(this IEnumerable<T> c, Action<T> a)
{
return new FirstPart<T>(c, a);
}
FirstRest rest<T>(this FirstPart<T> fp, Action<T> a)
{
return new FirstRest(fp.Collection, fp.Action, a);
}
You would need to define classed FirstPart and FirstRest. FirstRest would need a run method like so (Collection, FirstAction, and RestAction are properties):
void run()
{
bool first = true;
foreach (var x in Collection)
{
if (first) {
FirstAction(x);
first = false;
}
else {
RestAction(x);
}
}
}
Problem
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, what is the best way to code these loops? ``` // this is more code to read then I would like for such a common concept // and it is to easy to forget to update "firstItem" foreach (x in yyy) { if (firstItem) { firstItem = false; // other code when first item } // normal processing code } // this code is even harder to understand if (yyy.Length > 0) { //Process first item; for (int i = 1; i < yyy.Length; i++) { // process the other items. } } ```