Performant pagination in C#
Pagination on IEnumerable<> is typically done using .Skip() and .Take(). But if you want more than one page this is going to iterate over the enumerable multiple times. I don't feel like figuring it out, but the performance will definitely be worse than O(n). So here's a way to turn an enumerable into a paged enumerable of enumerables that iterates the original only once.
public static class IEnumerableExtensions
{
public static IEnumerable<IEnumerable<T>>(this IEnumerable<T> data, int pageSize)
{
var enumerator = data.GetEnumerator();
while(enumerator.MoveNext())
{
yield return GetPage(enumerator, pageSize);
}
static IEnumerable<T> GetPage(IEnumerator<T> enumerator, int pageSize)
{
var count = 0;
do
{
yield return enumerator.Current;
count++;
} while (count < pageSize && enumerator.MoveNext());
}
}
}