RaspberryIO_26/Swan.Lite/Paginator.cs

86 lines
2.9 KiB
C#
Raw Permalink Normal View History

2019-12-04 18:57:18 +01:00
using System;
2019-12-08 19:54:52 +01:00
namespace Swan {
/// <summary>
/// A utility class to compute paging or batching offsets.
/// </summary>
public class Paginator {
2019-12-04 18:57:18 +01:00
/// <summary>
2019-12-08 19:54:52 +01:00
/// Initializes a new instance of the <see cref="Paginator" /> class.
2019-12-04 18:57:18 +01:00
/// </summary>
2019-12-08 19:54:52 +01:00
/// <param name="totalCount">The total count of items to page over.</param>
/// <param name="pageSize">The desired size of individual pages.</param>
public Paginator(Int32 totalCount, Int32 pageSize) {
this.TotalCount = totalCount;
this.PageSize = pageSize;
this.PageCount = this.ComputePageCount();
}
/// <summary>
/// Gets the desired number of items per page.
/// </summary>
public Int32 PageSize {
get;
}
/// <summary>
/// Gets the total number of items to page over.
/// </summary>
public Int32 TotalCount {
get;
}
/// <summary>
/// Gets the computed number of pages.
/// </summary>
public Int32 PageCount {
get;
}
/// <summary>
/// Gets the start item index of the given page.
/// </summary>
/// <param name="pageIndex">Zero-based index of the page.</param>
/// <returns>The start item index.</returns>
public Int32 GetFirstItemIndex(Int32 pageIndex) {
pageIndex = this.FixPageIndex(pageIndex);
return pageIndex * this.PageSize;
}
/// <summary>
/// Gets the end item index of the given page.
/// </summary>
/// <param name="pageIndex">Zero-based index of the page.</param>
/// <returns>The end item index.</returns>
public Int32 GetLastItemIndex(Int32 pageIndex) {
Int32 startIndex = this.GetFirstItemIndex(pageIndex);
return Math.Min(startIndex + this.PageSize - 1, this.TotalCount - 1);
}
/// <summary>
/// Gets the item count of the given page index.
/// </summary>
/// <param name="pageIndex">Zero-based index of the page.</param>
/// <returns>The number of items that the page contains.</returns>
public Int32 GetItemCount(Int32 pageIndex) {
pageIndex = this.FixPageIndex(pageIndex);
return (pageIndex >= this.PageCount - 1) ? this.GetLastItemIndex(pageIndex) - this.GetFirstItemIndex(pageIndex) + 1 : this.PageSize;
}
/// <summary>
/// Fixes the index of the page by applying bound logic.
/// </summary>
/// <param name="pageIndex">Index of the page.</param>
/// <returns>A limit-bound index.</returns>
private Int32 FixPageIndex(Int32 pageIndex) => pageIndex < 0 ? 0 : pageIndex >= this.PageCount ? this.PageCount - 1 : pageIndex;
/// <summary>
/// Computes the number of pages for the paginator.
/// </summary>
/// <returns>The page count.</returns>
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;
}
2019-12-04 18:57:18 +01:00
}