扩展方法:
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;
你好我借用你的扩展方法在 Row[pd.Name] = pd.GetValue(item);这里老实报错,DataSet 不支持 System.Nullable<>。该如何解决呢请告诉下哦