一佳一

记录像1+1一样简洁的代码

导航

Ienumerable 转成table

Posted on 2010-10-12 15:43  一佳一  阅读(505)  评论(0编辑  收藏  举报
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;