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;
{
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;