發布時間:2020-11-30 11:57 作者:獨孤劍 閱讀:3482
using System; using System.Collections.Generic; using System.Data; using System.Reflection; namespace ConsoleApp1 { class Program { static void Main(string[] args) { // 創建一個新的DataTable DataTable dt = new DataTable("User"); dt.Columns.Add("UserName", typeof(string)); dt.Columns.Add("Password", typeof(string)); dt.Columns.Add("Age", typeof(int)); for (int i = 0; i < 5; ++i) { DataRow dr = dt.NewRow(); dr["UserName"] = "用戶名" + i.ToString(); dr["Password"] = "密碼" + i.ToString(); dr["Age"] = 20; dt.Rows.Add(dr); // DataTable 轉換為實體 User user = DataTableToModel<User>(dt); } // DataTable 轉換為List List<User> users = DataTableToList<User>(dt); } /// <summary> /// DataTable -> Model /// </summary> /// <typeparam name="T">數據項</typeparam> /// <param name="dt">DataTable</param> /// <returns></returns> public static T DataTableToModel<T>(DataTable dt) where T : new() { try { if (dt == null || dt.Rows.Count == 0) { return default(T); } T t = new T(); // 獲取行數據 DataRow dr = dt.Rows[0]; // 獲取欄目 DataColumnCollection columns = dt.Columns; // 獲得此模型的公共屬性 PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { string name = pi.Name; // 檢查DataTable是否包含此列 if (columns.Contains(name)) { if (!pi.CanWrite) continue; object value = dr[name]; if (value != DBNull.Value) { pi.SetValue(t, value, null); } } } return t; } catch { throw; } } /// <summary> /// DataTable -> List /// </summary> /// <typeparam name="T">數據項</typeparam> /// <param name="dt">DataTable</param> /// <returns></returns> public static List<T> DataTableToList<T>(DataTable dt) where T : new() { try { if (dt == null || dt.Rows.Count == 0) { return new List<T>(); } // 定義集合 List<T> list = new List<T>(); // 獲取欄目 DataColumnCollection columns = dt.Columns; foreach (DataRow dr in dt.Rows) { T t = new T(); // 獲得此模型的公共屬性 PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { string name = pi.Name; // 檢查DataTable是否包含此列 if (columns.Contains(name)) { if (!pi.CanWrite) continue; object value = dr[name]; if (value != DBNull.Value) { pi.SetValue(t, value, null); } } } list.Add(t); } return list; } catch { throw; } } } /// <summary> /// 用戶 /// </summary> public class User { /// <summary> /// 用戶名 /// </summary> public string UserName { get; set; } /// <summary> /// 密碼 /// </summary> public string Password { get; set; } /// <summary> /// 年齡 /// </summary> public int Age { get; set; } } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞