Using .Skip(...).Take(...)
will work for paging. But something to consider is that again an IEnumerable<...>
this will recalculate the enumerable each time it is processed. Is this is something that is consumed instead of being resettable you could have issues. This method set can fix this problem.
public static class EnumerableEx
{
public static IEnumerable<IEnumerable<T>> AsPages<T>(
this IEnumerable<T> set, int pageLength)
{
using (var e = set.GetEnumerator())
while (true)
yield return GetPage(e, pageLength);
}
private static IEnumerable<T> GetPage<T>(
IEnumerator<T> set, int pageLength)
{
for (var position = 0;
position < pageLength && set.MoveNext();
position++)
yield return set.Current;
}
}
... Here is a usage example of why it is important.
class Program
{
private static int _last = 0;
private static IEnumerable<int> GetValues()
{
while (true)
yield return _last++;
}
static void Main(string[] args)
{
for (var i = 0; i < 3; i++)
foreach (var value in GetValues().Skip(5 * i).Take(5))
Console.Write(value + ",");
// 0,1,2,3,4,10,11,12,13,14,25,26,27,28,29,
Console.WriteLine();
_last = 0;
foreach (var page in GetValues().AsPages(5).Take(3))
foreach (var value in page)
Console.Write(value + ",");
// 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,
}
}