using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; class Program { static void Main(string[] args) { var source = Enumerable.Range(0, 10000000); var sw = Stopwatch.StartNew(); var r = Windowed(source, 3).Count(); sw.Stop(); Console.WriteLine(r); Console.WriteLine(sw.Elapsed); } static IEnumerable Windowed(IEnumerable source, int windowSize) { if (source == null) throw new ArgumentNullException("source"); if (windowSize <= 0) throw new ArgumentOutOfRangeException("windowSize"); var arr = new T[windowSize]; int r = (windowSize - 1); int i = 0; foreach (var item in source) { arr[i] = item; i = (i + 1) % windowSize; if (r == 0) { var arrR = new T[windowSize]; for (int j = 0; j < windowSize; j++) arrR[j] = arr[(i + j) % windowSize]; yield return arrR; } else { r--; } } } }