1
Vote

SkipLast changes order of items

description

Example:
 
var source = Enumerable.Range(1, 30);
var items = source.SkipLast(10);
foreach (int i in items) Console.WriteLine(i);
 
Expected output: 1..20
Actual output: 2..10, 1, 11..20
 
Solution:
 
private static IEnumerable<TSource> SkipLastListIterator<TSource>(IEnumerable<TSource> source, int count)
{
var buffer = new Queue<TSource>(count);
using (var sourceEnumerator = source.GetEnumerator())
{
    while (buffer.Count != count && sourceEnumerator.MoveNext())
    {
        buffer.Enqueue(sourceEnumerator.Current);
    }
    while (sourceEnumerator.MoveNext())
    {
        yield return buffer.Dequeue();
        buffer.Enqueue(sourceEnumerator.Current);
    }
}
}

comments