Skip to content

Instantly share code, notes, and snippets.

@tejacques
Created March 10, 2014 03:55
Show Gist options
  • Save tejacques/9459222 to your computer and use it in GitHub Desktop.
Save tejacques/9459222 to your computer and use it in GitHub Desktop.
IEnumerable extension for all but the last n elements of a sequence.
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