Created
July 7, 2019 10:09
-
-
Save jotatoledo/8ed338da00da3abcd3b0b138634c104f to your computer and use it in GitHub Desktop.
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
// 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