C#簡單的通用分頁



通用分頁技術分析

  • 需要返回不同的類型的數據--采用泛型實現該操作
  • 需要提供不同的方法
    1. 上一頁
    2. 上一頁
    3. 第一頁
    4. 最后一頁
    5. 跳轉到指定頁

Demo 代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBAManagement
{
    /// <summary>
    /// 通過的分頁類
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Paging<T>
    {
        public List<T> DataSource = new List<T>();

        public int PageIndex { get; set; }
        public int AllPage { get; set; }
        public int EachCount { get; set; }
        
        
        public Paging(List<T> dataSource, int eachCount)
        {
            this.DataSource = dataSource;
            this.AllPage = (int)Math.Ceiling((double)this.DataSource.Count / eachCount);
            this.EachCount = eachCount;
            this.PageIndex = 1;
        }
        //下一頁
        public List<T> Next()
        {
            PageIndex++;
            if (this.PageIndex > AllPage)
                PageIndex--;
            return GetPage();
        }
        //上一頁
        public List<T> Provious()
        {
            PageIndex--;
            if (this.PageIndex == 0)
                PageIndex++;
            return GetPage();
        }
        //第一頁
        public List<T> Fist()
        {
            this.PageIndex = 1;
            return GetPage();
        }
        //最后一頁
        public List<T> End()
        {
            this.PageIndex = this.AllPage;
            return GetPage();
        }

        /// <summary>
        /// 跳轉到指定的頁
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public List<T> GoTo(int index)
        {
            if (index <= 0)
                index = 1;
            if (index >= AllPage)
                index = AllPage;
            this.PageIndex = index;
            return GetPage();
        }

        /// <summary>
        /// 獲得當前頁
        /// </summary>
        /// <returns></returns>
        private List<T> GetPage()
        {
            return this.DataSource.Skip((PageIndex - 1) * EachCount).Take(EachCount).ToList();
        }
    }
}

后記

通過這樣的一個類基本實現了大多數的情況下的分頁操作(雖然可能性能不是很高),這里主要是運用了泛型的特性來幫助我們返回任意的對象集。只需要在UI中做一些簡單的處理即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM