-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPagingExtensions.cs
37 lines (33 loc) · 1.22 KB
/
PagingExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;
using System.Collections.Generic;
using System.Linq;
namespace Samples.Common.Extensions
{
public static class PagingExtensions // aka slicing / creating slices
{
public static IEnumerable<TSource> Page<TSource>(this IEnumerable<TSource> source, int page, int pageSize)
{
return source.Skip((page - 1) * pageSize).Take(pageSize);
}
public static IEnumerable<List<TSource>> Pages<TSource>(this IEnumerable<TSource> source, int pageSize)
{
var pages = source.Select((x, index) => new
{
Index = index / pageSize,
Value = x
}).GroupBy(x => x.Index).Select(x => x.Select(y => y.Value).ToList());
return pages.ToList();
}
public static IEnumerable<TResult> PageSelect<TItem, TResult>(
this IEnumerable<TItem> items, Func<IEnumerable<TItem>, IEnumerable<TResult>> select, int pageSize)
{
foreach (var batch in items.Pages(pageSize))
{
foreach (var result in select(batch))
{
yield return result;
}
}
}
}
}