本文实例讲述了C#将DataTable转换成list及数据分页的方法。分享给大家供大家参考。具体如下:
/// 酒店评论列表-分页
/// </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
telorder.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;
}</div>
将一个DataTable转换成一个List
首先定义一个接收DataTable字段列的类 。类的字段与DataTable的列字段一致
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1
{
/// <summary>
/// 用户信息
/// </summary>
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public int Age { get; set; }
public int Gender { get; set; }
}
}</div>
using System.Collections.Generic;
using System.Linq;
using System.Web;
using JSON.Controllers;
using System.Data;
namespace WebApplication1
{
public class Class1
{
/// <summary>
/// 将DataTable转换成一个list
/// </summary>
/// <returns>返回一个List<User>对象</returns>
public List<User> TableToList()
{
string sql = "select * from T_User"; //T_User表里总共有 id,UserName,Age,Gender四列
DataTable dt= SqlHelper.ExecuteDataTable(sql,null);
var list = new List<User>(); //创建一个List<User>的实例
if (dt != null && dt.Rows.Count > 0)
{
&nbs