-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathPagedResult.cs
More file actions
51 lines (44 loc) · 1.75 KB
/
PagedResult.cs
File metadata and controls
51 lines (44 loc) · 1.75 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace Dotnet5.GraphQL3.Repositories.Abstractions.Pages
{
public class PagedResult<T>
{
private readonly int _index;
private readonly IEnumerable<T> _items;
private readonly int _size;
public PagedResult(IEnumerable<T> items, int index, int size)
{
_items = items;
_index = index;
_size = size;
}
public IEnumerable<T> Items
=> _items.Take(_size);
public PageInfo PageInfo
=> new()
{
Current = _index,
Size = Items.Count(),
HasNext = _size < _items.Count(),
HasPrevious = _index > 1
};
public static async Task<PagedResult<T>> CreateAsync(IQueryable<T> source, PageParams pageParams, CancellationToken cancellationToken)
{
pageParams ??= new();
var items = await ApplyPagination(source, pageParams).ToListAsync(cancellationToken);
return new PagedResult<T>(items, pageParams.Index, pageParams.Size);
}
public static PagedResult<T> Create(IQueryable<T> source, PageParams pageParams)
{
pageParams ??= new();
var items = ApplyPagination(source, pageParams).ToList();
return new PagedResult<T>(items, pageParams.Index, pageParams.Size);
}
private static IQueryable<T> ApplyPagination(IQueryable<T> source, PageParams pageParams)
=> source.Skip(pageParams.Size * (pageParams.Index - 1)).Take(pageParams.Size + 1);
}
}