public static DataTable ToDataTable<T>(IEnumerable<T> varlist) { DataTable dtReturn = new DataTable(); // column names PropertyInfo[] oProps = null; if (varlist == null) return dtReturn; foreach (T rec in varlist) { if (oProps == null) { oProps = ((Type)rec.GetType()).GetProperties(); foreach (PropertyInfo pi in oProps) { Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) { colType = colType.GetGenericArguments()[0]; } dtReturn.Columns.Add(new DataColumn(pi.Name, colType)); } } DataRow dr = dtReturn.NewRow(); foreach (PropertyInfo pi in oProps) { dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue (rec, null); } dtReturn.Rows.Add(dr); } return dtReturn; }
用扩展方法你当作LINQ一样的用吧
public static DataTable CopyToDataTable<T>(this IEnumerable<T> list)
{
var pList = new List<PropertyInfo>();
var type = typeof(T);
var dt = new DataTable();
Array.ForEach(type.GetProperties(), p =>
{
pList.Add(p);
dt.Columns.Add(p.Name);
});
foreach (var item in list)
{
DataRow row = dt.NewRow();
pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
dt.Rows.Add(row);
}
return dt;
}
谢谢,帮助。有点忙,结贴 结的有点晚,,
first
return data[0];这种就是反回一个datatable吧。
list<string>怎么返回一个string? list[1]这种就返回一个string了啊。