Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Personally I like Mark Byer's option, but you could always write your own generic method for this:</p> <pre><code>public static void IterateWithSpecialFirst&lt;T&gt;(this IEnumerable&lt;T&gt; source, Action&lt;T&gt; firstAction, Action&lt;T&gt; subsequentActions) { using (IEnumerator&lt;T&gt; iterator = source.GetEnumerator()) { if (iterator.MoveNext()) { firstAction(iterator.Current); } while (iterator.MoveNext()) { subsequentActions(iterator.Current); } } } </code></pre> <p>That's relatively straightforward... giving a special <em>last</em> action is slightly harder:</p> <pre><code>public static void IterateWithSpecialLast&lt;T&gt;(this IEnumerable&lt;T&gt; source, Action&lt;T&gt; allButLastAction, Action&lt;T&gt; lastAction) { using (IEnumerator&lt;T&gt; iterator = source.GetEnumerator()) { if (!iterator.MoveNext()) { return; } T previous = iterator.Current; while (iterator.MoveNext()) { allButLastAction(previous); previous = iterator.Current; } lastAction(previous); } } </code></pre> <p>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 <em>not</em> 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 <em>that</em> isn't "common". If I ever run into it, I'll special-case that particular code, and the best solution will depend on <em>exactly</em> what the code needs to do.</p> <p>In general, however, I value readability and reusability <em>much</em> more than micro-optimization.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload