public static DataTable ObjectToTable(object obj)
{
try {
Type t;
if (obj.GetType().IsGenericType)
{
t = obj.GetType().GetGenericTypeDefinition();
}
else
{
t = obj.GetType();
}
if(t== typeof(List<>)||
t==typeof(IEnumerable<>))
{
DataTable dt = new DataTable();
IEnumerable<object> lstenum=obj as IEnumerable<object>;
if(lstenum.Count()>0)
{
var ob1 = lstenum.GetEnumerator();
ob1.MoveNext();
foreach (var item in ob1.Current.GetType().GetProperties())
{
dt.Columns.Add(new DataColumn() { ColumnName = item.Name });
}
//数据
foreach (var item in lstenum)
{
DataRow row = dt.NewRow();
foreach (var sub in item.GetType().GetProperties())
{
row[sub.Name] = sub.GetValue(item, null);
}
dt.Rows.Add(row);
}
return dt;
}
}
else if (t == typeof(DataTable))
{
return (DataTable)obj;
}
else //(t==typeof(Object))
{
DataTable dt = new DataTable();
foreach (var item in obj.GetType().GetProperties())
{
dt.Columns.Add(new DataColumn() { ColumnName=item.Name });
}
DataRow row= dt.NewRow();
foreach (var item in obj.GetType().GetProperties())
{
row[item.Name] = item.GetValue(obj, null);
}
dt.Rows.Add(row);
return dt;
}
}catch(Exception ex)
{
}
return null;
}
相关文章
- 07-24将对象集合List
转换为DataTable - 07-24DataTable转List,DataTable转为Model对象帮助类
- 07-24List转DataTable
- 07-245-14 EF使用存储过程以及LIST泛型对象转换为Datatable
- 07-24C# List集合转换成DataTable
- 07-24datatable 转list ,list转datatable
- 07-24C# DataTable 和List之间相互转换的方法
- 07-24jackson简单使用,对象转json,json转对象,json转list
- 07-24jackson 转 list map 对象
- 07-24SQLServer -------- 一表多用,将关联的表变成字符串存储(C# 字符转datatable)