DataTable转List
public static ListToListModel (this DataTable table) where T : new() { var type = typeof(T); var properties = type.GetProperties(); List list = new List (); foreach (DataRow row in table.Rows) { var t = Activator.CreateInstance (); 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) { Dictionarydata = new Dictionary (); List > parentRow = new List >(); data.Add("total", total); data.Add("rows", CreateRows(table)); return data; } private static object CreateRows(DataTable table) { List > parentRow = new List >(); Dictionary childRow; foreach (DataRow row in table.Rows) { childRow = new Dictionary (); 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; }