.net使用linq進行分頁

來源:互聯網
上載者:User

昨天看了一會linq的書.今天哪來練練手.寫了個簡單的linq分頁.在這裡拿出來與大家共用一下.適合小資料型分頁.因為他是先讀取完全資料,然後在進行分頁.

好了直接貼出代碼

首頁建立一個aspx頁面

然後在後台aspx.cs檔案中

 1  protected void Page_Load(object sender, EventArgs e)
 2         {
 3             if (!IsPostBack)
 4             {
 5                 int CurPage = 1;
 6                 int PageSize = 5;
 7                 int.TryParse(Request["CurPage"], out CurPage);
 8                 if (CurPage == 0)
 9                     CurPage = 1;
10                 //擷取總資料集合
11                 IList<ContentsModel> objs = new List<ContentsModel>();
12                 objs = Contents.GetAllContents();
13                 //綁定資料顯示控制項
14                 GridView1.DataSource = QueryByPage(PageSize, CurPage, objs);
15                 GridView1.DataBind();
16                 //擷取分頁目錄
17                 this.Label1.Text = GetQueryPagesMenu(PageSize, objs);
18             }
19         }
20         /// <summary>
21         /// 輸入分頁字元頁碼
22         /// </summary>
23         /// <param name="PageSize"></param>
24         /// <param name="objs"></param>
25         /// <returns></returns>
26         protected string GetQueryPagesMenu(int PageSize, IList<ContentsModel> objs)
27         {
28             int Count;
29             var db = objs;
30             var query = from cms_contents in db select cms_contents;
31             Count = (query.Count() / PageSize + 1);//不足一頁按一頁算
32             string PageMenu = "";
33             //拼接分頁目錄
34             for (int i = 1; i <= Count; i++)
35             {
36                 PageMenu += "<a href='?CurPage=" + i.ToString() + "'>" + i.ToString() + "</a>&nbsp;|&nbsp;";
37             }
38             return PageMenu;
39         }
40         /// <summary>
41         /// 擷取分頁後的資料集
42         /// </summary>
43         /// <param name="PageSize">每頁顯示的記錄數</param>
44         /// <param name="CurPage">頁數</param>
45         /// <param name="objs">資料總集合</param>
46         /// <returns></returns>
47         protected List<ContentsModel> QueryByPage(int PageSize, int CurPage, IList<ContentsModel> objs)
48         {
49             var query = from cms_contents in objs select cms_contents;
50             return query.Take(PageSize * CurPage).Skip(PageSize * (CurPage - 1)).ToList(); 

51         } 

 樣式在這裡就不多寫了.

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.