Skip to content

Instantly share code, notes, and snippets.

@restlessmedia
Created October 10, 2016 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save restlessmedia/f57a6b275837b141bb89c15f3795a59b to your computer and use it in GitHub Desktop.
Save restlessmedia/f57a6b275837b141bb89c15f3795a59b to your computer and use it in GitHub Desktop.
public static class LinqExtensions
{
public static IQueryable<TSource> Page<TSource>(this IQueryable<TSource> source, IPageable pageable)
{
return Page<IQueryable<TSource>, TSource>(source, pageable);
}
public static IQueryable<TSource> Page<TSource>(this IQueryable<TSource> source, int page, int maxPerPage = 10)
{
return Page<IQueryable<TSource>, TSource>(source, page, maxPerPage);
}
public static IEnumerable<TSource> Page<TSource>(this IEnumerable<TSource> source, IPageable pageable)
{
return Page<IEnumerable<TSource>, TSource>(source, pageable);
}
public static IEnumerable<TSource> Page<TSource>(this IEnumerable<TSource> source, int page, int maxPerPage = 10)
{
return Page<IEnumerable<TSource>, TSource>(source, page, maxPerPage);
}
public static T Page<T, TSource>(this IEnumerable<TSource> source, IPageable pageable)
where T : IEnumerable<TSource>
{
if (pageable == null)
throw new ArgumentNullException("pageable");
return Page<T, TSource>(source, pageable.Page, pageable.MaxPerPage);
}
public static T Page<T, TSource>(this IEnumerable<TSource> source, int page, int maxPerPage = 10)
where T : IEnumerable<TSource>
{
if (source == null)
throw new ArgumentNullException("source");
if (page < 1)
throw new ArgumentNullException("page", "page needs to be a positive number");
if (maxPerPage < 1)
throw new ArgumentNullException("maxPerPage", "maxPerPage needs to be a positive number");
if (page == 1)
return (T)source.Take(maxPerPage);
int skip = (page - 1) * maxPerPage;
return (T)source.Skip(skip).Take(maxPerPage);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment