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;
        }
    }
View Code

相关文章:

  • 2021-11-29
  • 2021-08-20
  • 2021-09-04
  • 2021-09-14
  • 2021-08-28
  • 2021-07-11
猜你喜欢
  • 2021-10-26
  • 2022-01-06
  • 2021-12-09
  • 2022-12-23
  • 2021-11-24
  • 2021-07-08
  • 2022-12-23
相关资源
相似解决方案