在用Linq查询中,常常需要用到分页功能,因为每次都需要些分页这些功能,于是把分页功能提取出来,不喜大家勿喷,只是贴出来,自觉地很实用。一下贴出核心代码:
1 ///2 /// LinqHelper 主要用于数据集,排序 分页等功能 3 /// 4 public class LinqHelper 5 { 6 ///7 /// 排序 8 /// 9 ///10 /// 11 /// 12 /// 13 /// 14 public static IQueryable DataSorting (IQueryable source, string sortExpression, string sortDirection)15 {16 string sortingDir = string.Empty;17 if (sortDirection.ToUpper().Trim() == "ASC")18 sortingDir = "OrderBy";19 else if (sortDirection.ToUpper().Trim() == "DESC")20 sortingDir = "OrderByDescending";21 ParameterExpression param = Expression.Parameter(typeof(T), sortExpression);22 PropertyInfo pi = typeof(T).GetProperty(sortExpression);23 Type[] types = new Type[2];24 types[0] = typeof(T);25 types[1] = pi.PropertyType;26 Expression expr = Expression.Call(typeof(Queryable), sortingDir, types, source.Expression, Expression.Lambda(Expression.Property(param, sortExpression), param));27 IQueryable query = source.AsQueryable().Provider.CreateQuery (expr);28 return query;29 }30 /// 31 /// 分页32 /// 33 ///34 /// 35 /// 36 /// 37 /// 38 public static IQueryable DataPaging (IQueryable source, int pageNumber, int pageSize)39 {40 return source.Skip((pageNumber - 1) * pageSize).Take(pageSize);41 }42 /// 43 /// 排序并分页 44 /// 45 ///46 /// 47 /// 48 /// 49 /// 50 /// 51 /// 52 public static IQueryable SortingAndPaging (IQueryable source, string sortExpression, string sortDirection, int pageNumber, int pageSize)53 {54 if (!string.IsNullOrEmpty(sortDirection))55 {56 // IQueryable query = DataSorting (source, sortExpression, sortDirection);57 }58 IQueryable query = source.AsQueryable();59 return DataPaging(query, pageNumber, pageSize);60 }61 }
在分页中需要一个辅助的类用于分页排序的类,用于限定分页的参数:
1 //排序用到的参数 2 public class GridPager 3 { 4 ///5 /// //每页行数 6 /// 7 public int rows { get; set; } 8 ///9 /// //当前页是第几页10 /// 11 public int page { get; set; }12 ///13 /// //排序方式14 /// 15 public string order { get; set; }16 ///17 /// //排序列18 /// 19 public string sort { get; set; }20 ///21 /// //总行数 22 /// 23 public int totalRows { get; set; } 24 }
使用方法*.ASP中 XXXX.ashx一般处理程序中,调用方法为:
1 public void GetAllInfoRW(HttpContext context) 2 { 3 string retStr = ""; 4 string rowsStr = ""; 5 int rCount = 0; 6 GridPager pager = new GridPager 7 { 8 page = Convert.ToInt32(context.Request["page"]), 9 rows = Convert.ToInt32(context.Request["rows"]),10 sort = "RTime",11 order = "DESC"12 };13 string chk = context.Request["chk"].ToString();14 Listlist = CCRK_CKDBiz.GetAllShowInfo(chk,ref rCount);15 var resout = LinqHelper.SortingAndPaging(list.AsQueryable(), pager.sort, pager.sort, pager.page, pager.rows);16 rowsStr = JsonConvert.SerializeObject(list);17 18 retStr = "{\"total\":\"" + rCount + "\",\"rows\":" + rowsStr + "}";19 20 context.Response.Write(retStr);21 }
在easyui-datagrid中注意json格式
在使用JsonConvert.SerializeObject(object); 方法中需要引入命名空间,【using Newtonsoft.Json】可以通过可以通过Nuget程序管理工具在http://www.nuget.org/官网上下载
在VS中通过Nuget程序管理工具输入命令:Install-Package Newtonsoft.Json