PageFilter.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace NBAManagment.Filter
  7. {
  8. public class PageFilter<T> : IFilter<T>
  9. {
  10. public int CurrentPageNum { get; set; }
  11. public int PageSize { get; set; }
  12. public PageFilter(int pageSize, int currentPageNum)
  13. {
  14. this.PageSize = pageSize;
  15. this.CurrentPageNum = currentPageNum;
  16. }
  17. public int GetPageCount(IEnumerable<T> collection)
  18. {
  19. var itemsCount = collection.Count();
  20. var incompletePageCount = (itemsCount % PageSize) > 0 ? 1 : 0;
  21. return itemsCount / PageSize + incompletePageCount;
  22. }
  23. private bool IsNumInPage(int pageNum)
  24. {
  25. int firstElementOnCurrentPageNum = PageSize * (CurrentPageNum - 1) + 1;
  26. return pageNum >= firstElementOnCurrentPageNum &&
  27. pageNum <= (firstElementOnCurrentPageNum + PageSize - 1);
  28. }
  29. public IEnumerable<T> Use(IEnumerable<T> collection)
  30. {
  31. bool elementsFind = false;
  32. int currentPageNum = 1;
  33. var resultCollection = new List<T>();
  34. foreach (var item in collection)
  35. {
  36. if (IsNumInPage(currentPageNum))
  37. {
  38. resultCollection.Add(item);
  39. elementsFind = true;
  40. }
  41. else if (elementsFind)
  42. {
  43. break;
  44. }
  45. currentPageNum++;
  46. }
  47. return resultCollection;
  48. }
  49. }
  50. }