1
Vote

TakeLast changes order of items

description

Example:
 
var source = Enumerable.Range(1, 25);
var items = source.TakeLast(10);
foreach (int i in items) Console.WriteLine(i);
 
Expected output: 16..25
Actual output: 20..16, 25..21
 
Solution:
 
private static IEnumerable<TSource> TakeLastIterator<TSource>(IEnumerable<TSource> source, int count)
{
var buffer = new Queue<TSource>(count);
foreach (var item in source)
{
    if (buffer.Count == count) buffer.Dequeue();
    buffer.Enqueue(item);
}

return buffer;
}

comments