If you need to βpaginationβ several times in your solution, you can use the extension method.
Hacked in LINQPad, it will do the trick.
public static class MyExtensions { public static IEnumerable<IEnumerable<T>> Paginate<T>(this IEnumerable<T> source, int pageSize) { T[] buffer = new T[pageSize]; int index = 0; foreach (var item in source) { buffer[index++] = item; if (index >= pageSize) { yield return buffer.Take(pageSize); index = 0; } } if (index > 0) { yield return buffer.Take(index); } } }
Basically, it fills the buffer with pageSize size and gives it when it is pageSize . If there are < pageSize elements left, we also give them. Thus,
Enumerable.Range(1, 10).Paginate(3).Dump();
will give
{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10}}
source share