zoukankan      html  css  js  c++  java
  • Ienumerable 转成table

    public static DataTable ConvertToDataTable(this IEnumerable enumerable)
    {
        var dataTable = new DataTable();
        foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(T))) {
               dataTable.Columns.Add(pd.Name, pd.PropertyType);
        }
        foreach (T item in enumerable) {
               var Row = dataTable.NewRow();
                   
           foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))  {
                     Row[pd.Name] = pd.GetValue(item);
           }
        dataTable.Rows.Add(Row);
       }
       return dataTable;

    }

    传统写法:
    DataTable table = new DataTable();
    table.Columns.Add("UserID", typeof (long));
    table.Columns.Add("UserName", typeof (string));

    IEnumerable<T> database = //获取数据源;
        foreach (T info in database) {
            DataRow row = dt.NewRow();
            row["ID"] = database.ID;
            row["Name"] = database.Name;
            table.Rows.Add(row);
         }
    }
    return table;

  • 相关阅读:
    1059. C语言竞赛(20)
    1057. 数零壹(20)
    1056. 组合数的和(15)
    1054. 求平均值 (20)
    1052. 卖个萌 (20)
    1053. 住房空置率 (20)
    第五周课后作业02(动手动脑)
    课堂动手动脑
    课后作业
    课堂测试动手动脑
  • 原文地址:https://www.cnblogs.com/linyijia/p/1848879.html
Copyright © 2011-2022 走看看