C#Object转DataTable C# Object 转 DataTable
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())
{
object to
row[item.Name]= item.GetValue(obj,null);
}
dt.Rows.Add(row);
return dt;
}
}
catch(Exception ex)
{
}
return null;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。