public class TableHelper { public static DataTable CreateTableFromClass(Type t) { DataTable dt = new DataTable(); PropertyInfo[] pis = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); int colNum = t.GetProperties().Count(); for (int c = 0; c < colNum; c++) { dt.Columns.Add(pis[c].Name, typeof(string)); } return dt; } public static DataTable ConvertListToTable<T>(List<T> stores, DataTable dt) where T : class { Type objType = typeof(T); int colNum = objType.GetProperties().Count(); DataColumnCollection cols = dt.Columns; if (stores.Count > 0) { for (int r = 0; r < stores.Count; r++) { var store = stores[r]; DataRow dr = dt.NewRow(); for (int c = 0; c < colNum; c++) { PropertyInfo pi = objType.GetProperty(cols[c].ColumnName, BindingFlags.Public | BindingFlags.Instance); object value = pi.GetValue(store, null); dr[c] = value; } dt.Rows.Add(dr); } } return dt; } }
相关文章: