using System; namespace Swan { /// /// A utility class to compute paging or batching offsets. /// public class Paginator { /// /// Initializes a new instance of the class. /// /// The total count of items to page over. /// The desired size of individual pages. public Paginator(Int32 totalCount, Int32 pageSize) { this.TotalCount = totalCount; this.PageSize = pageSize; this.PageCount = this.ComputePageCount(); } /// /// Gets the desired number of items per page. /// public Int32 PageSize { get; } /// /// Gets the total number of items to page over. /// public Int32 TotalCount { get; } /// /// Gets the computed number of pages. /// public Int32 PageCount { get; } /// /// Gets the start item index of the given page. /// /// Zero-based index of the page. /// The start item index. public Int32 GetFirstItemIndex(Int32 pageIndex) { pageIndex = this.FixPageIndex(pageIndex); return pageIndex * this.PageSize; } /// /// Gets the end item index of the given page. /// /// Zero-based index of the page. /// The end item index. public Int32 GetLastItemIndex(Int32 pageIndex) { Int32 startIndex = this.GetFirstItemIndex(pageIndex); return Math.Min(startIndex + this.PageSize - 1, this.TotalCount - 1); } /// /// Gets the item count of the given page index. /// /// Zero-based index of the page. /// The number of items that the page contains. public Int32 GetItemCount(Int32 pageIndex) { pageIndex = this.FixPageIndex(pageIndex); return (pageIndex >= this.PageCount - 1) ? this.GetLastItemIndex(pageIndex) - this.GetFirstItemIndex(pageIndex) + 1 : this.PageSize; } /// /// Fixes the index of the page by applying bound logic. /// /// Index of the page. /// A limit-bound index. private Int32 FixPageIndex(Int32 pageIndex) => pageIndex < 0 ? 0 : pageIndex >= this.PageCount ? this.PageCount - 1 : pageIndex; /// /// Computes the number of pages for the paginator. /// /// The page count. private Int32 ComputePageCount() => // include this if when you always want at least 1 page this.TotalCount == 0 ? 0 : this.TotalCount % this.PageSize != 0 ? (this.TotalCount / this.PageSize) + 1 : this.TotalCount / this.PageSize; } }