1. 程式人生 > >C#中DataTable的建立與遍歷

C#中DataTable的建立與遍歷

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; }
}