C's method of converting DataTable to list

  • 2020-12-13 19:04:42
  • OfStack

This article gives an example of how C# translates DataTable to list and data paging. Share to everybody for everybody reference. The details are as follows:

/// <summary>  
 /// Hotel Review list - paging  
/// </summary> 
/// <param name="userId"></param> 
/// <param name="pageIndex"> The current page </param> 
/// <param name="pageCount"> Total number of pages </param> 
/// <returns></returns> 
 public static List<CommentInfo> GetHotelCommentList(int userId, int pageIndex, out int pageCount) 
 { 
     var list = new List<CommentInfo>(); 
     pageCount = 0; 
     try 
     { 
         // Query the hotel ID, The name , The picture , The user ID, User comments  
         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()  // this list Find out all the user reviews  
                     select new CommentInfo 
                     { 
                         Id = p.Field<int>("hid"), //p.Filed<int>("Id") It's really about getting DataRow In the ID The column. That is: row["ID"] 
                         HotelImages = p.Field<string>("images"), 
                         HotelName = p.Field<string>("hotelName"), 
                         Comment = p.Field<string>("comment") 
                     }).ToList(); // Convert this set to list 
             int pageSize = 10; // Each page shows 10 The data  
 
             // Get total pages  
             pageCount = list.Count % pageSize == 0 ? ((list.Count - pageSize >= 0 ? (list.Count / pageSize) : (list.Count == 0 ? 0 : 1))) : list.Count / pageSize + 1; 
 
             // this list Is taken to 10 The data  
             //Skip Skips the specified number of elements in the sequence, and returns the remaining elements.  
             //Take The beginning of a sequence returns a specified number of consecutive elements.  
             list = list.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList(); // Assume the current page is at number 1 3 Page. So I'm going to skip over here 10*(3-1) The skip 20 The data, Take(pageSize) mean : take 10 The data , Now that I've skipped the previous one 20 So that's the number. So here's the number 21 So let's go. Take 10 The cough up  
         } 
     } 
     catch (Exception ex) 
     { 
         // write log here 
     } 
     return list; 
}

Convert 1 DataTable to 1 List
First define a class that accepts the DataTable field column. The field of the class is sent to column field 1 of DataTable

using System;  
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
 
namespace WebApplication1 

    /// <summary> 
    /// The user information  
    /// </summary> 
    public class User 
    { 
        public int Id { get; set; } 
 
        public string UserName { get; set; } 
 
        public int Age { get; set; } 
 
        public int Gender { get; set; } 
    } 
}

using System;  
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using JSON.Controllers; 
using System.Data; 
 
namespace WebApplication1 

    public class Class1 
    { 
        /// <summary> 
        /// will DataTable Converted to 1 a list 
        /// </summary> 
        /// <returns> return 1 a List<User> object </returns> 
        public List<User> TableToList() 
        { 
            string sql = "select  * from T_User"; //T_User There are all of them id,UserName,Age,Gender4 column  
            DataTable dt= SqlHelper.ExecuteDataTable(sql,null); 
            var list = new List<User>(); // create 1 a List<User> An instance of the  
            if (dt != null && dt.Rows.Count > 0) 
            { 
                //AsEnumerable() Returns the 1 a IEnumerable<T> Object whose generic parameters T for System.Data.DataRow .  
                list = (from p in dt.AsEnumerable() 
                        select new User  //new1 a User object  
                        { 
                            Id = p.Field<int>("id"),//p.Filed<int>("id") It's really about getting DataRow In the ID The column. That is: row["ID"] And then assign it to User Of the class Id Field.  
                            UserName = p.Field<string>("UserName"), 
                            Age = p.Field<int>("Age"), 
                            Gender = p.Field<int>("Gender") 
                        }).ToList(); // Will this User Class object to list 
            } 
            int dataCount = list.Count; // Total number of data bars.  
            int pageSize=10;// How many pieces of data are displayed per page.              
            int pageCount; // The total number of pages.  
            int currentPage=3;// The current page. -- This assumes that the current page is page 1 3 Page.  
            pageCount = dataCount % pageSize == 0 ? (dataCount < pageSize ? (dataCount==0?0:1): (dataCount / pageSize)) : (dataCount / pageSize + 1);       // this list Is taken to 10 The data    
            //Skip Skips the specified number of elements in the sequence, and returns the remaining elements.    
            //Take The beginning of a sequence returns a specified number of consecutive elements.    
            list = list.Skip(pageSize * (currentPage - 1)).Take(pageSize).ToList(); // Assume the current page is at number 1 3 Page. So I'm going to skip over here 10*(3-1) The skip 20 The data, Take(pageSize) mean : take 10 The data , Now that I've skipped the previous one 20 So that's the number. So here's the number 21 So let's go. Take 10 The cough up    
            return list;  
        }         
    } 
}

Hopefully this article has helped you with your C# programming.


Related articles: