C#中DataTable的創建與遍歷實現

1、創建DataTable對象

/// <summary>
/// 創建DataTable對象
/// </summary>
public static DataTable CreateDataTable()
{
  //創建DataTable
  DataTable dt = new DataTable("NewDt");
      
  //創建自增長的ID列
  DataColumn dc = dt.Columns.Add("ID", Type.GetType("System.Int32"));
  dc.AutoIncrement = true;  //自動增加
  dc.AutoIncrementSeed = 1; //起始為1
  dc.AutoIncrementStep = 1; //步長為1
  dc.AllowDBNull = false;  //非空
 
  //創建其它列表
  dt.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));
  dt.Columns.Add(new DataColumn("Age", Type.GetType("System.Int32")));
  dt.Columns.Add(new DataColumn("Score", Type.GetType("System.Decimal")));
  dt.Columns.Add(new DataColumn("CreateTime", Type.GetType("System.DateTime")));
 
  //創建數據
  DataRow dr = dt.NewRow();
  dr["Name"] = "張三";
  dr["Age"] = 28;
  dr["Score"] = 85.5;
  dr["CreateTime"] = DateTime.Now;
  dt.Rows.Add(dr);
 
  dr = dt.NewRow();
  dr["Name"] = "李四";
  dr["Age"] = 24;
  dr["Score"] = 72;
  dr["CreateTime"] = DateTime.Now;
  dt.Rows.Add(dr);
 
  dr = dt.NewRow();
  dr["Name"] = "王五";
  dr["Age"] = 36;
  dr["Score"] = 63.5;
  dr["CreateTime"] = DateTime.Now;
  dt.Rows.Add(dr);
 
  return dt;
}

2、遍歷DataTable對象

/// <summary>
/// 遍歷DataTable對象,轉換成List對象
/// </summary>
public static List<UserInfo> TraverseDataTable(DataTable dt)
{
  List<UserInfo> userList = new List<UserInfo>();
 
  //判斷DataTable是否為空
  if (dt == null || dt.Rows.Count == 0)
  {
    return null;
  }
 
  //遍歷DataTable對象,轉換成List
  foreach (DataRow row in dt.Rows)
  {
    UserInfo user = new UserInfo();
 
    if (dt.Columns.Contains("ID") && !Convert.IsDBNull(row["ID"]))
      user.ID = Convert.ToInt32(row["ID"]);
 
    if (dt.Columns.Contains("Name") && !Convert.IsDBNull(row["Name"]))
      user.Name = Convert.ToString(row["Name"]);
 
    if (dt.Columns.Contains("Age") && !Convert.IsDBNull(row["Age"]))
      user.Age = Convert.ToInt32(row["Age"]);
 
    if (dt.Columns.Contains("Score") && !Convert.IsDBNull(row["Score"]))
      user.Score = Convert.ToDouble(row["Score"]);
 
    if (dt.Columns.Contains("CreateTime") && !Convert.IsDBNull(row["CreateTime"]))
      user.CreateTime = Convert.ToDateTime(row["CreateTime"]);
 
    userList.Add(user);
  }
 
  return userList;
}

其它代碼:

/// <summary>
/// 用戶信息類
/// </summary>
public class UserInfo
{
  /// <summary>
  /// 編號
  /// </summary>
  public int ID { get; set; }
 
  /// <summary>
  /// 名稱
  /// </summary>
  public string Name { get; set; }
 
  /// <summary>
  /// 年齡
  /// </summary>
  public int Age { get; set; }
 
  /// <summary>
  /// 成績
  /// </summary>
  public double Score { get; set; }
 
  /// <summary>
  /// 創建時間
  /// </summary>
  public DateTime CreateTime { get; set; }
}

到此這篇關於C#中DataTable的創建與遍歷實現的文章就介紹到這瞭,更多相關C# DataTable創建與遍歷內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: