我有一个从数据库中检索数据并将其添加到列表中的函数.我的列表已准备好并显示数据,但我希望在该列表上进行分页,以便每页显示有限的记录.但不知道如何做到这一点.
这是我的数据层功能的代码.
public List<demodto> executereader(List<demodto> Ldemo,SqlCommand cmdshow, string tablename)
{
SqlConnection cn;
try
{
cn = this.getconnection();
cmdshow.Connection = cn;
cn.Open();
SqlDataReader rd = cmdshow.ExecuteReader();
while (rd.Read())
{
demodto dtoobj1 = new demodto();
dtoobj1.ID = Convert.ToInt32(rd[0].ToString());
dtoobj1.Name = rd[1].ToString();
dtoobj1.PhNo = Convert.ToInt32(rd[2].ToString());
dtoobj1.Address = rd[3].ToString();
dtoobj1.Gender = rd[4].ToString();
dtoobj1.Email = rd[5].ToString();
dtoobj1.Emptype = rd[6].ToString();
Ldemo.Add(dtoobj1);
}
cn.Close();
return Ldemo;
}
catch (Exception ex2)
{
throw new DataException("error....." + ex2.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
这是DTO课程..
public class demodto
{
public Int32 ID{get;set;}
public string Name{get;set;}
public Int32 PhNo { get; set; }
public string Address{get;set;}
public string Gender { get; set; }
public string Email { get; set; }
public string Emptype { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
请帮我.谢谢.
das*_*ght 28
您可以使用LINQ页面列表,如下所示:
IList<demodto> GetPage(IList<demodto> list, int page, int pageSize) {
return list.Skip(page*pageSize).Take(pageSize).ToList();
}
Run Code Online (Sandbox Code Playgroud)
例如,假设每个页面有50条记录.要获得第三页,请致电
IList<demodto> thirdPage = GetPage(dataList, 3, 50);
Run Code Online (Sandbox Code Playgroud)
但是请注意,对内存中的数据应用分页几乎没有意义:分页背后的想法是减少从数据库中检索数据所需的时间,并通过只保留一个页面来节省一些内存,在您的情况下不会发生,因为所有数据都会立即被检索.
为了使分页值得付出努力,您需要将其移动到数据库中.更改方法以接受页面大小和编号,并使用它们更改SQL以检索单个页面的列表.不要忘记在sql读取时强制排序,否则相同的数据可能会出现在不同的页面上.您的SQL需要修改以支持分页.根据您的数据库,这会有所不同.本答案中描述了 MS SQL Server解决方案.
| 归档时间: |
|
| 查看次数: |
18627 次 |
| 最近记录: |