Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>EDIT: added usage example, added a ForFirst method, reordered my paragraphs.</p> <p>Below is a complete solution.</p> <p>Usage is either of the following:</p> <pre><code> list.ForFirst(DoWorkForFirst).ForRemainder(DoWork); // or list.ForNext(1, DoWorkForFirst).ForRemainder(DoWork); </code></pre> <p>The crux is the <code>ForNext</code> method, which performs an action for the specified next set of items from the collection and returns the remaining items. I've also implemented a <code>ForFirst</code> method that simply calls ForNext with count: 1.</p> <pre><code>class Program { static void Main(string[] args) { List&lt;string&gt; list = new List&lt;string&gt;(); // ... list.ForNext(1, DoWorkForFirst).ForRemainder(DoWork); } static void DoWorkForFirst(string s) { // do work for first item } static void DoWork(string s) { // do work for remaining items } } public static class EnumerableExtensions { public static IEnumerable&lt;T&gt; ForFirst&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable, Action&lt;T&gt; action) { return enumerable.ForNext(1, action); } public static IEnumerable&lt;T&gt; ForNext&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable, int count, Action&lt;T&gt; action) { if (enumerable == null) throw new ArgumentNullException("enumerable"); using (var enumerator = enumerable.GetEnumerator()) { // perform the action for the first &lt;count&gt; items of the collection while (count &gt; 0) { if (!enumerator.MoveNext()) throw new ArgumentOutOfRangeException(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Unexpected end of collection reached. Expected {0} more items in the collection.", count)); action(enumerator.Current); count--; } // return the remainder of the collection via an iterator while (enumerator.MoveNext()) { yield return enumerator.Current; } } } public static void ForRemainder&lt;T&gt;(this IEnumerable&lt;T&gt; enumerable, Action&lt;T&gt; action) { if (enumerable == null) throw new ArgumentNullException("enumerable"); foreach (var item in enumerable) { action(item); } } } </code></pre> <p>I felt a bit ridiculous making the <code>ForRemainder</code> method; I could swear that I was re-implementing a built-in function with that, but it wasn't coming to mind and I couldn't find an equivalent after glancing around a bit. UPDATE: After reading the other answers, I see there apparently isn't an equivalent built into Linq. I don't feel so bad now.</p>
 

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