淺析LINQ通用分頁(yè)綁定方法的實(shí)現(xiàn)
在這里我們將討論LINQ通用分頁(yè)綁定方法,希望通過(guò)本文能對(duì)大家了解LINQ通用分頁(yè)有所幫助,在這里將展示更多的代碼。
#T#
在LINQ中,IQueryable <T>接口和IEnumerable <T>接口都分別提供了Skip方法和Take方法,用來(lái)做分頁(yè)非常合適.因此我就想用他們做一個(gè)分頁(yè)控件,因?yàn)镮Queryable <T> 是繼承自 IEnumerable <T> 的。因此使用接口僅需要針對(duì)后者就可以了。使用的時(shí)候只需提供數(shù)據(jù)源、綁定的GridView的、每頁(yè)大小即可?,F(xiàn)在問(wèn)題就出了在數(shù)據(jù)源上,要求用戶提供一個(gè)數(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的類型只有在運(yùn)行時(shí)才能得到,怎么辦呢!其實(shí)很簡(jiǎn)單我,我們可以使用 “參數(shù)推導(dǎo)泛型類型”的方法來(lái)實(shí)現(xiàn):
看下面的代碼(因?yàn)橹攸c(diǎn)不在這里所以 代碼寫(xiě)的比較粗糙):
- public void BindBoundControl<TSource>(IEnumerable<TSource> DataSource, GridView BoundControl, int PageSize)
- {
- //獲取總記錄數(shù)(這里可以使用參數(shù)傳入總頁(yè)數(shù) 就不必每次都執(zhí)行下面方法)
- int totalRecordCount = DataSource.Count();
- //計(jì)算總頁(yè)數(shù)
- int totalPageCount = 0;
- if (PageSize == 0)
- {
- PageSize = totalRecordCount;
- }
- if (totalRecordCount % PageSize == 0)
- {
- totalPageCount = totalRecordCount / PageSize;
- }
- else
- {
- totalPageCount = totalRecordCount / PageSize + 1;
- }
- //從參數(shù)中獲取當(dāng)前頁(yè)碼
- int CurrentPageIndex = 1;
- //如果從參數(shù)中獲取頁(yè)碼不正確 設(shè)置頁(yè)碼為第一頁(yè)
- 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);
- }
下面我們只是需要重載一下我們的分頁(yè)方法實(shí)現(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);
- }
這個(gè)方法很簡(jiǎn)單的 只是通過(guò) list.FirstOrDefault() 做參數(shù) 來(lái)推導(dǎo) 方法中 BindBoundControl<TSource> 的TSource 就可以了,當(dāng)然因?yàn)槊看畏猪?yè)時(shí)都會(huì)執(zhí)行 list.FirstOrDefault() 會(huì)損失一點(diǎn)點(diǎn)的效率。
原文標(biāo)題:非常簡(jiǎn)單的實(shí)現(xiàn)LINQ通用分頁(yè)綁定方法
鏈接:http://www.cnblogs.com/ejiyuan/archive/2009/12/22/1629806.html