發布時間:2020-11-30 11:57 作者:獨孤劍 閱讀:1363
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Reflection; namespace ConsoleApp1 { class Program { static void Main(string[] args) { User user = new User(); user.UserName = "用戶名"; user.Password = "密碼"; user.Age = 20; List<User> users = new List<User>(); for (int i = 0; i < 5; ++i) { user = new User(); user.UserName = "用戶名" + i.ToString(); user.Password = "密碼" + i.ToString(); user.Age = 20; users.Add(user); } // Model -> DataTable DataTable dt1 = ModelToDataTable<User>(user); // List<> -> DataTable DataTable dt2 = ListToDataTable<User>(users); } /// <summary> /// Model -> DataTable /// </summary> /// <typeparam name="T">數據項</typeparam> /// <param name="data"></param> /// <returns></returns> public static DataTable ModelToDataTable<T>(T data) { try { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); DataTable dt = new DataTable(); // 創建欄 for (int i = 0; i < properties.Count; i++) { PropertyDescriptor property = properties[i]; dt.Columns.Add(property.Name, property.PropertyType); } object[] values = new object[properties.Count]; // 賦值 for (int i = 0; i < values.Length; i++) { values[i] = properties[i].GetValue(data); } dt.Rows.Add(values); return dt; } catch { throw; } } /// <summary> /// List -> DataTable /// </summary> /// <typeparam name="T">數據項</typeparam> /// <param name="list"></param> /// <returns></returns> public static DataTable ListToDataTable<T>(IList<T> list) { try { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); DataTable dt = new DataTable(); // 創建欄 for (int i = 0; i < properties.Count; i++) { PropertyDescriptor property = properties[i]; dt.Columns.Add(property.Name, property.PropertyType); } object[] values = new object[properties.Count]; // 賦值 foreach (T item in list) { for (int i = 0; i < values.Length; i++) { values[i] = properties[i].GetValue(item); } dt.Rows.Add(values); } return dt; } 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; } } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞