Last active
March 19, 2021 08:01
-
-
Save rgueldenpfennig/ed2ace12dd5511418905235227717284 to your computer and use it in GitHub Desktop.
Simple paging functionality for Entity Framework queries
This file contains hidden or 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
| public static class PagingExtensions | |
| { | |
| public static IQueryable<T> Page<T>(this IQueryable<T> query, int pageIndex, int pageSize) | |
| { | |
| if (pageSize < 1) throw new ArgumentOutOfRangeException(nameof(pageSize), "Must be greater than zero."); | |
| if (pageIndex < 0) throw new ArgumentOutOfRangeException(nameof(pageIndex), "Must not be negative."); | |
| if (pageIndex != 0) query = query.Skip(pageIndex * pageSize); | |
| return query.Take(pageSize); | |
| } | |
| public static async Task<IEnumerable<T>> Page<T>(this IQueryable<T> query, int pageSize) | |
| { | |
| var list = new List<T>(); | |
| var count = await query.CountAsync(); | |
| var totalPages = (int)Math.Ceiling(count / (double)pageSize); | |
| for (int i = 0; i < totalPages; i++) | |
| { | |
| var batch = await query.Page(i, pageSize).ToListAsync(); | |
| list.AddRange(batch); | |
| } | |
| return list; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment