明天的明天 永远的永远 未知的一切 我与你一起承担 ??

是非成败转头空 青山依旧在 几度夕阳红 。。。
  博客园  :: 首页  :: 管理

C# 将DataTable转换成list (--分页--) 【Skip--Take】

Posted on 2019-02-15 09:19  且行且思  阅读(1160)  评论(0编辑  收藏  举报

将DataTable转换成list 及数据分页:

/// <summary>
/// 酒店评论列表-分页
/// </summary>
/// <param name="userId"></param>
/// <param name="pageIndex">当前页</param>
/// <param name="pageCount">总页数</param>
/// <returns></returns>
public static List<CommentInfo> GetHotelCommentList(int userId, int pageIndex, out int pageCount)
{
    var list = new List<CommentInfo>();
    pageCount = 0;
    try
    {
        //查询酒店ID,名字,图片,用户ID,用户评论
        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 
		on hotelorder.UserID=user_HotelComment.userID on hotels.hid=hotelorder.HotelID where hotelorder.UserID={0}", userId);
        DataTable dt = SQLHelper.Get_DataTable(sql, SQLHelper.GetCon(), null);
 
        if (dt != null && dt.Rows.Count > 0)
        {
         
            list = (from p in dt.AsEnumerable()  //这个list是查出全部的用户评论
                    select new CommentInfo
                    {
                        Id = p.Field<int>("hid"), //p.Filed<int>("Id") 其实就是获取DataRow中ID列。即:row["ID"]
                        HotelImages = p.Field<string>("images"),
                        HotelName = p.Field<string>("hotelName"),
                        Comment = p.Field<string>("comment")
                    }).ToList(); //将这个集合转换成list
 
            int pageSize = 10; //每页显示十条数据
 
            //获取总页数
            pageCount = list.Count % pageSize == 0 ? ((list.Count - pageSize >= 0 ? (list.Count / pageSize) :(list.Count == 0 ? 0 : 1))) : list.Count / pageSize + 1;
 
            //这个list 就是取到10条数据
            //Skip跳过序列中指定数量的元素,然后返回剩余的元素。
            //Take序列的开头返回指定数量的连续元素。
            list = list.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList(); //假设当前页为第三页。这么这里就是跳过 10*(3-1) 即跳过20条数据,Take(pageSize)的意思是:取10条数据,既然前面已经跳过前20条数据了,那么这里就是从21条开始,取10条咯
            
 
        }
 
    }
    catch (Exception ex)
    {
        // write log here
    }
    return list;
 
 
}

 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>();