Last active
September 12, 2019 09:03
-
-
Save jbrestan/18db80101122a169fd1b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Pagination as a function | |
static IQueryable<T> Paginate<T>(this IQueryable<T> query, int pageNumber, int pageSize) => | |
query.Skip(pageSize*pageNumber).Take(pageSize); | |
// Usage | |
var paginatedQuery = originalQuery.Paginate(pageNumber, pageSize); | |
// Composition (fluent with extension methods) | |
var paginatedFilteredQuery = originalQuery.Where(predicate).Paginate(pageNumber, pageSize); | |
// Composition (classical) | |
var filteredQuery = Where(originalQuery, predicate); | |
var paginatedFilteredQuery = Paginate(filteredQuery, pageNumber, pageSize); | |
// Pagination as a decorator | |
class PaginatedQuery<T> : IQueryable<T> | |
{ | |
private readonly IQueryable<T> query; | |
public PaginatedQuery(IQueryable<T> query, int pageNumber, int pageSize) | |
{ | |
// Basically the same as Paginate function, that's why I prefer the function | |
this.query = query.Skip(pageSize*pageNumber).Take(pageSize); | |
} | |
#region IQueryable<T> implementation... | |
public Type ElementType => query.ElementType; | |
public Expression Expression => query.Expression; | |
public IQueryProvider Provider => query.Provider; | |
public IEnumerator<T> GetEnumerator() => query.GetEnumerator(); | |
#endregion | |
} | |
// Usage | |
var paginatedQuery = new PaginatedQuery(originalQuery, pageNumber, pageSize); | |
// Composition | |
var filteredQuery = new FilteredQuery(originalQuery, predicate); | |
var paginatedFilteredQuery = new PaginatedQuery(filteredQuery, pageNumber, pageSize); | |
// Combination - ridiculous in this case but that's how Skip, Take, Where and other combinators are often defined. | |
static IQueryable<T> Paginate<T>(this IQueryable<T> query, int pageNumber, int pageSize) => | |
new PaginatedQuery(query, pageNumber, pageSize); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment