zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#将DataTable转换成list的方法

c#List方法 转换成 dataTable
2023-06-13 09:15:41 时间

本文实例讲述了C#将DataTable转换成list及数据分页的方法。分享给大家供大家参考。具体如下:

复制代码代码如下:

///<summary> 
 ///酒店评论列表-分页 
///</summary> 
///<paramname="userId"></param> 
///<paramname="pageIndex">当前页</param> 
///<paramname="pageCount">总页数</param> 
///<returns></returns> 
 publicstaticList<CommentInfo>GetHotelCommentList(intuserId,intpageIndex,outintpageCount) 
 { 
    varlist=newList<CommentInfo>(); 
    pageCount=0; 
    try 
    { 
        //查询酒店ID,名字,图片,用户ID,用户评论 
        stringsql=string.Format(@"selecthotels.hid,hotels.hotelName,hotels.images,hotelorder.UserID,user_HotelComment.commentfromhotelswith(nolock)joinhotelorderwith(nolock)joinuser_HotelComment  
telorder.UserID=user_HotelComment.userIDonhotels.hid=hotelorder.HotelIDwherehotelorder.UserID={0}",userId); 
        DataTabledt=SQLHelper.Get_DataTable(sql,SQLHelper.GetCon(),null); 
        if(dt!=null&&dt.Rows.Count>0) 
        { 
            list=(frompindt.AsEnumerable() //这个list是查出全部的用户评论 
                    selectnewCommentInfo 
                    { 
                        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 
            intpageSize=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(Exceptionex) 
    { 
        //writeloghere 
    } 
    returnlist; 
}

将一个DataTable转换成一个List
首先定义一个接收DataTable字段列的类。类的字段与DataTable的列字段一致

复制代码代码如下:
usingSystem; 
usingSystem.Collections.Generic; 
usingSystem.Linq; 
usingSystem.Web; 
 
namespaceWebApplication1 

   ///<summary> 
   ///用户信息 
   ///</summary> 
   publicclassUser 
   { 
       publicintId{get;set;} 
 
       publicstringUserName{get;set;} 
 
       publicintAge{get;set;} 
 
       publicintGender{get;set;} 
   } 
}

复制代码代码如下:usingSystem; 
usingSystem.Collections.Generic; 
usingSystem.Linq; 
usingSystem.Web; 
usingJSON.Controllers; 
usingSystem.Data; 
 
namespaceWebApplication1 

   publicclassClass1 
   { 
       ///<summary> 
       ///将DataTable转换成一个list 
       ///</summary> 
       ///<returns>返回一个List<User>对象</returns> 
       publicList<User>TableToList() 
       { 
           stringsql="select *fromT_User";//T_User表里总共有id,UserName,Age,Gender四列 
           DataTabledt=SqlHelper.ExecuteDataTable(sql,null); 
           varlist=newList<User>();//创建一个List<User>的实例 
           if(dt!=null&&dt.Rows.Count>0) 
           { 
               //AsEnumerable():返回一个IEnumerable<T>对象,其泛型参数T为System.Data.DataRow。 
               list=(frompindt.AsEnumerable() 
                       selectnewUser //new一个User对象 
                       { 
                           Id=p.Field<int>("id"),//p.Filed<int>("id")其实就是获取DataRow中ID列。即:row["ID"]然后将它赋值给User类的Id字段。 
                           UserName=p.Field<string>("UserName"), 
                           Age=p.Field<int>("Age"), 
                           Gender=p.Field<int>("Gender") 
                       }).ToList();//将这个User类对象转换成list 
           } 
           intdataCount=list.Count;//总的数据条数。 
           intpageSize=10;//每页显示多少条数据。             
           intpageCount;//总页数。 
           intcurrentPage=3;//当前页。--这里假设当前页为第3页。 
           pageCount=dataCount%pageSize==0?(dataCount<pageSize?(dataCount==0?0:1):(dataCount/pageSize)):(dataCount/pageSize+1); 

    //这个list就是取到10条数据   
           //Skip跳过序列中指定数量的元素,然后返回剩余的元素。   
           //Take序列的开头返回指定数量的连续元素。   
           list=list.Skip(pageSize*(currentPage-1)).Take(pageSize).ToList();//假设当前页为第3页。这么这里就是跳过10*(3-1)即跳过20条数据,Take(pageSize)的意思是:取10条数据,既然前面已经跳过前20条数据了,那么这里就是从21条开始,取10条咯   
           returnlist;  
       }         
   } 
}

希望本文所述对大家的C#程序设计有所帮助。