Skip to content

Instantly share code, notes, and snippets.

@jotatoledo
Created July 7, 2019 10:09
Show Gist options
  • Save jotatoledo/8ed338da00da3abcd3b0b138634c104f to your computer and use it in GitHub Desktop.
Save jotatoledo/8ed338da00da3abcd3b0b138634c104f to your computer and use it in GitHub Desktop.
// Based on https://codereview.stackexchange.com/a/223655/145828
static public IEnumerable<T> SkipLast<T>(this IEnumerable<T> data, int count)
{
if (data == null) throw new ArgumentNullException(nameof(data));
if (count <= 0) return data;
if (data is ICollection<T> collection)
return collection.Take(collection.Count - count);
IEnumerable<T> Skipper()
{
using (var enumer = data.GetEnumerator())
{
T[] queue = new T[count];
int index = 0;
while (index < count && enumer.MoveNext())
queue[index++] = enumer.Current;
index = -1;
while (enumer.MoveNext())
{
index = (index + 1) % count;
yield return queue[index];
queue[index] = enumer.Current;
}
}
}
return Skipper();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment