淺析LINQ通用分頁綁定方法的實現(xiàn)
在這里我們將討論LINQ通用分頁綁定方法,希望通過本文能對大家了解LINQ通用分頁有所幫助,在這里將展示更多的代碼。
#T#
在LINQ中,IQueryable <T>接口和IEnumerable <T>接口都分別提供了Skip方法和Take方法,用來做分頁非常合適.因此我就想用他們做一個分頁控件,因為IQueryable <T> 是繼承自 IEnumerable <T> 的。因此使用接口僅需要針對后者就可以了。使用的時候只需提供數(shù)據(jù)源、綁定的GridView的、每頁大小即可。現(xiàn)在問題就出了在數(shù)據(jù)源上,要求用戶提供一個數(shù)據(jù)源類型,即IQueryable <T>接口和IEnumerable <T>接口? T是可確定類型(已知類型)的話還可以,若T是匿名類型,如
- var list = from it in de.Customers where it.City == "abc" select new { it.City, it.Country };
list的類型只有在運行時才能得到,怎么辦呢!其實很簡單我,我們可以使用 “參數(shù)推導(dǎo)泛型類型”的方法來實現(xiàn):
看下面的代碼(因為重點不在這里所以 代碼寫的比較粗糙):
- public void BindBoundControl<TSource>(IEnumerable<TSource> DataSource, GridView BoundControl, int PageSize)
- {
- //獲取總記錄數(shù)(這里可以使用參數(shù)傳入總頁數(shù) 就不必每次都執(zhí)行下面方法)
- int totalRecordCount = DataSource.Count();
- //計算總頁數(shù)
- int totalPageCount = 0;
- if (PageSize == 0)
- {
- PageSize = totalRecordCount;
- }
- if (totalRecordCount % PageSize == 0)
- {
- totalPageCount = totalRecordCount / PageSize;
- }
- else
- {
- totalPageCount = totalRecordCount / PageSize + 1;
- }
- //從參數(shù)中獲取當(dāng)前頁碼
- int CurrentPageIndex = 1;
- //如果從參數(shù)中獲取頁碼不正確 設(shè)置頁碼為第一頁
- if (!int.TryParse(HttpContext.Current.Request.QueryString["Page"], out CurrentPageIndex) || CurrentPageIndex <= 0 || CurrentPageIndex > totalPageCount)
- {
- CurrentPageIndex = 1;
- }
- //綁定數(shù)據(jù)源
- BoundControl.DataSource = DataSource.Skip((CurrentPageIndex - 1) * PageSize).Take(PageSize);
- BoundControl.DataBind();
- }
調(diào)用
- protected void Page_Load(object sender, EventArgs e)
- {
- NorthwindEntities de = new NorthwindEntities();
- BindingUtils bind = new BindingUtils();
- //先排序與一下再綁定
- bind.BindBoundControl<Customers>(de.Customers.OrderBy(v=>v.CustomerID), this.GridView1, 10);
- }
下面我們只是需要重載一下我們的分頁方法實現(xiàn)“參數(shù)推導(dǎo)泛型類型”就可以了 代碼如下:
- public void BindBoundControl<TSource>(IEnumerable<TSource> DataSource, TSource type, GridView BoundControl, int PageSize)
- {
- this.BindBoundControl(DataSource, BoundControl, PageSize);
- }
調(diào)用
- protected void Page_Load(object sender, EventArgs e)
- {
- NorthwindEntities de = new NorthwindEntities();
- var list = from it in de.Customers where it.City == "abc" select new { it.City, it.Country };
- BindingUtils bind = new BindingUtils();
- bind.BindBoundControl(list.OrderBy(c=>c.City), list.FirstOrDefault(), this.GridView1, 10);
- }
這個方法很簡單的 只是通過 list.FirstOrDefault() 做參數(shù) 來推導(dǎo) 方法中 BindBoundControl<TSource> 的TSource 就可以了,當(dāng)然因為每次分頁時都會執(zhí)行 list.FirstOrDefault() 會損失一點點的效率。
原文標(biāo)題:非常簡單的實現(xiàn)LINQ通用分頁綁定方法
鏈接:http://www.cnblogs.com/ejiyuan/archive/2009/12/22/1629806.html