DataTable转List
public static List<T> ToListModel<T>(this DataTable table) where T : new() { var type = typeof(T); var properties = type.GetProperties(); List<T> list = new List<T>(); foreach (DataRow row in table.Rows) { var t = Activator.CreateInstance<T>(); foreach (var p in properties) { if (!table.Columns.Contains(p.Name)) continue; if ((row[p.Name]).GetType() != typeof(DBNull)) p.SetValue(t, row[p.Name], null); } list.Add(t); t = default(T); } return list; }
DataTable转Object
public static object DataTableToObject(this DataTable table, int total) { Dictionary<string, object> data = new Dictionary<string, object>(); List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>(); data.Add("total", total); data.Add("rows", CreateRows(table)); return data; } private static object CreateRows(DataTable table) { List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>(); Dictionary<string, object> childRow; foreach (DataRow row in table.Rows) { childRow = new Dictionary<string, object>(); foreach (DataColumn col in table.Columns) { bool isDate = false; #region 时间转化 if (col.ColumnName.Contains("_DATE") || col.ColumnName.Contains("_TIME") || col.ColumnName.Contains("_DT") || col.ColumnName.Contains("FDATE")) { isDate = true; } #endregion if (isDate) { try { childRow.Add(col.ColumnName, row[col] is DBNull ? "" : Convert.ToDateTime(row[col]).ToString("yyyy-MM-dd")); } catch { childRow.Add(col.ColumnName, row[col]); } } else { childRow.Add(col.ColumnName, row[col]); } } parentRow.Add(childRow); } return parentRow; }