List<>对象转换成dataTable
private DataTable changeDataTable(object lst模块)
{
DataTable dt = new DataTable();
IList list = (IList)lst模块;
// use reflection to discover all properties of the object
BindingFlags bf = BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty;
PropertyInfo[] props = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in props)
dt.Columns.Add(pi.Name,Type.GetType(pi.PropertyType.FullName));
foreach (object obj in list)
{
DataRow dr = dt.NewRow();
foreach (PropertyInfo pi in props)
{
object result = obj.GetType().InvokeMember(pi.Name, bf, null, obj, null);
// d.Add(result);
dr[pi.Name] = result;
}
dt.Rows.Add(dr);
}
return dt;
}
本文介绍了一种将List对象转换为DataTable的方法。通过反射获取对象的所有属性,并将其添加到DataTable的列中,然后遍历List中的每个对象,使用InvokeMember方法获取属性值并填充到DataTable的行中。
1427

被折叠的 条评论
为什么被折叠?



