将DataTable转换成list 及数据分页:
1/// <summary> 2/// 酒店评论列表-分页 3/// </summary> 4/// <param name="userId"></param> 5/// <param name="pageIndex">当前页</param> 6/// <param name="pageCount">总页数</param> 7/// <returns></returns> 8public static List<CommentInfo> GetHotelCommentList(int userId, int pageIndex, out int pageCount) 9{ 10 var list = new List<CommentInfo>(); 11 pageCount = 0; 12 try 13 { 14 //查询酒店ID,名字,图片,用户ID,用户评论 15 string sql = string.Format( @"select hotels.hid,hotels.hotelName,hotels.images,hotelorder.UserID,user_HotelComment.comment from hotels with(nolock) join hotelorder with(nolock) join user_HotelComment 16 on hotelorder.UserID=user_HotelComment.userID on hotels.hid=hotelorder.HotelID where hotelorder.UserID={0}", userId); 17 DataTable dt = SQLHelper.Get_DataTable(sql, SQLHelper.GetCon(), null); 18 19 if (dt != null && dt.Rows.Count > 0) 20 { 21 22 list = (from p in dt.AsEnumerable() //这个list是查出全部的用户评论 23 select new CommentInfo 24 { 25 Id = p.Field<int>("hid"), //p.Filed<int>("Id") 其实就是获取DataRow中ID列。即:row["ID"] 26 HotelImages = p.Field<string>("images"), 27 HotelName = p.Field<string>("hotelName"), 28 Comment = p.Field<string>("comment") 29 }).ToList(); //将这个集合转换成list 30 31 int pageSize = 10; //每页显示十条数据 32 33 //获取总页数 34 pageCount = list.Count % pageSize == 0 ? ((list.Count - pageSize >= 0 ? (list.Count / pageSize) :(list.Count == 0 ? 0 : 1))) : list.Count / pageSize + 1; 35 36 //这个list 就是取到10条数据 37 //Skip跳过序列中指定数量的元素,然后返回剩余的元素。 38 //Take序列的开头返回指定数量的连续元素。 39 list = list.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList(); //假设当前页为第三页。这么这里就是跳过 10*(3-1) 即跳过20条数据,Take(pageSize)的意思是:取10条数据,既然前面已经跳过前20条数据了,那么这里就是从21条开始,取10条咯 40 41 42 } 43 44 } 45 catch (Exception ex) 46 { 47 // write log here 48 } 49 return list; 50 51 52}
C# AsEnumerable 找不到 ?? 添加引用 System.Data.DataSetExtensions
DataTable dt = new DataTable();
var test = dt.AsEnumerable();
//跳过dt的前200行,取后100行 即取得200-300行
test.Skip(200).Take(100);
或
dt = dt.AsEnumerable().Take(N).CopyToDataTable<DataRow>();