Last active
October 17, 2023 11:44
-
-
Save btastic/5a3e8605fb2ed104a9fc9c91b92a32a5 to your computer and use it in GitHub Desktop.
Pagination with dots in C#
This file contains 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 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