linq - Most elegant way to process first IEnumerable item differently -


what elegant way process first ienumerable item differently others, without having test on each iteration?

with test on each iteration, this:

// "first item done" flag bool firstdone = false;  // items ienumerable<something> foreach (var item in items) {     if (!firstdone)     {         // once         processdifferently(item);         firstdone = true;         continue;     }      processnormally(item); } 

if this:

processdifferently(items.first()); processnormally(items.skip(1)); // calls `items.getenumerator` again 

it invoke getenumerator twice, avoid (for linq-to-sql cases, example).

how it, if need several times around code?

if needed in several places, i'd extract method:

public void process<t>(ienumerable<t> source,                        action<t> firstaction,                        action<t> remainderaction) {     // todo: argument validation     using (var iterator = source.getenumerator())     {         if (iterator.movenext())         {             firstaction(iterator.current);         }         while (iterator.movenext())         {             remainderaction(iterator.current);         }     } } 

called as:

process(items, processdifferently, processnormally); 

there other options too, depend on situation.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -