public static DataSet
ToDataSet(
this object obj)
{
if (obj ==
null)
return null;
if (obj
is DataSet)
{
return obj
as DataSet;
}
DataSet ds =
new DataSet();
if (obj
is DataTable)
{
ds.Tables.Add(obj
as DataTable);
return ds;
}
DataTable dt =
new DataTable();
ds.Tables.Add(dt);
IEnumerable<
object> list = obj
as IEnumerable<
object>;
if (list ==
null)
{
var properties = obj.GetType().GetProperties().ToList();
if (properties.Count ==
0)
return null;
properties.ForEach(s => dt.Columns.Add(s.Name, Nullable.GetUnderlyingType(s.PropertyType) ?? s.PropertyType));
var row = dt.NewRow();
properties.ForEach(s => row[s.Name] = s.GetValue(obj,
null) ?? DBNull.Value);
dt.Rows.Add(row);
}
else
{
try
{
var properties = list.ToList()[
0].GetType().GetProperties().ToList();
properties.ForEach(s => dt.Columns.Add(s.Name, Nullable.GetUnderlyingType(s.PropertyType) ?? s.PropertyType));
foreach (
var i
in list)
{
var row = dt.NewRow();
properties.ForEach(s => row[s.Name] = s.GetValue(i,
null) ?? DBNull.Value);
dt.Rows.Add(row);
}
}
catch (Exception)
{
return null;
}
}
return ds;
}
转载请注明原文地址: https://ju.6miu.com/read-677291.html