Created
March 10, 2014 03:55
-
-
Save tejacques/9459222 to your computer and use it in GitHub Desktop.
IEnumerable extension for all but the last n elements of a sequence.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace System.Linq | |
{ | |
public static class ExceptLastLinq | |
{ | |
public static IEnumerable<T> ExceptLast<T>( | |
this IEnumerable<T> source) | |
{ | |
if (source == null) | |
throw new ArgumentNullException("source"); | |
return InternalExceptLast(source); | |
} | |
private static IEnumerable<T> InternalExceptLast<T>( | |
IEnumerable<T> source) | |
{ | |
T buffer = default(T); | |
bool buffered = false; | |
foreach (T x in source) | |
{ | |
if (buffered) | |
yield return buffer; | |
buffer = x; | |
buffered = true; | |
} | |
} | |
public static IEnumerable<T> ExceptLast<T>( | |
this IEnumerable<T> source, int n) | |
{ | |
if (source == null) | |
throw new ArgumentNullException("source"); | |
if (n < 0) | |
throw new ArgumentOutOfRangeException("n", | |
"Argument n should be non-negative."); | |
return InternalExceptLast(source, n); | |
} | |
private static IEnumerable<T> InternalExceptLast<T>( | |
IEnumerable<T> source, int n) | |
{ | |
Queue<T> buffer = new Queue<T>(n + 1); | |
foreach (T x in source) | |
{ | |
buffer.Enqueue(x); | |
if (buffer.Count == n + 1) | |
yield return buffer.Dequeue(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment