Skip to content

Instantly share code, notes, and snippets.

@btastic
Last active October 17, 2023 11:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save btastic/5a3e8605fb2ed104a9fc9c91b92a32a5 to your computer and use it in GitHub Desktop.
Save btastic/5a3e8605fb2ed104a9fc9c91b92a32a5 to your computer and use it in GitHub Desktop.
Pagination with dots in C#
public class Pagination
{
public int PageIndex { get; private set; }
public int TotalPages { get; private set; }
public List<object> RangeWithDots { get; private set; } = new List<object>();
public bool HasPreviousPage
{
get
{
return (PageIndex > 1);
}
}
public bool HasNextPage
{
get
{
return (PageIndex < TotalPages);
}
}
public Pagination(int index, int totalPages)
{
PageIndex = index;
TotalPages = totalPages;
RangeWithDots = Maker(PageIndex, TotalPages);
}
private static List<object> Maker(int c, int m)
{
int current = c;
int last = m;
int delta = 4;
int left = current - delta;
int right = current + delta + 1;
List<int> range = new List<int>();
List<object> rangeWithDots = new List<object>();
int l = 0;
for (int i = 1; i <= last; i++)
{
if (i == 1 || i == last || i >= left && i < right)
{
range.Add(i);
}
}
foreach (var item in range)
{
if (l > 0)
{
if (item - l == 2)
{
rangeWithDots.Add(l + 1);
}
else if (item - l != 1)
{
rangeWithDots.Add("...");
}
}
rangeWithDots.Add(item);
l = item;
}
return rangeWithDots;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment