C# DataTable 互轉 List<T>
阿新 • • 發佈:2021-07-22
1.新增幫助類DataTableHelper.cs
public static class DataTableHelper { /// <summary> /// List轉DataTable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <returns></returns> public static DataTable ConvertTo<T>(IList<T> list) { DataTable table= CreateTable<T>(); Type entityType = typeof(T); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType); foreach (T item in list) { DataRow row = table.NewRow(); foreach (PropertyDescriptor prop in properties) row[prop.Name]= prop.GetValue(item); table.Rows.Add(row); } return table; } private static DataTable CreateTable<T>() { Type entityType = typeof(T); DataTable table = new DataTable(entityType.Name); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);foreach (PropertyDescriptor prop in properties) table.Columns.Add(prop.Name, prop.PropertyType); return table; } /// <summary> /// DataTable轉List /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <returns></returns> public static IList<T> ConvertTo<T>(DataTable table) { if (table == null) return null; List<DataRow> rows = new List<DataRow>(); foreach (DataRow row in table.Rows) rows.Add(row); return ConvertTo<T>(rows); } private static IList<T> ConvertTo<T>(IList<DataRow> rows) { IList<T> list = null; if (rows != null) { list = new List<T>(); foreach (DataRow row in rows) { T item = CreateItem<T>(row); list.Add(item); } } return list; } //將資料行轉換為T物件 private static T CreateItem<T>(DataRow row) { string columnName; T obj = default(T); if (row != null) { obj = Activator.CreateInstance<T>(); foreach (DataColumn column in row.Table.Columns) { columnName = column.ColumnName; //獲取具有相同列名的屬性 PropertyInfo prop = obj.GetType().GetProperty(columnName); try { //獲取列的值 object value = (row[columnName].GetType() == typeof(DBNull)) ? null : row[columnName]; //設定屬性值 if (prop.CanWrite) //判斷其是否可寫 prop.SetValue(obj, value, null); } catch { } } } return obj; } }
2. 建立實體類
public class User { public string ID { get; set; } public string Name { get; set; } }
3.實現
DataTable dt = new DataTable(); dt.Columns.Add("ID"); dt.Columns.Add("Name"); dt.Rows.Add("1", "哈哈哈"); dt.Rows.Add("2", "嘎嘎"); IList<User> list = DataTableHelper.ConvertTo<User>(dt); DataTable dt1 = DataTableHelper.ConvertTo<User>(list);