将数组对象转换成DataSet
public static DataSet ObjectArrayToDataSet(object[] objArr)
{
if (objArr.Length == 0)
return null;
DataSet ds = CreateDataSet(objArr[0].GetType());
ds = FillDataSet(ds, objArr);
return ds;
}
public static DataSet CreateDataSet(Type t)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
System.Reflection.PropertyInfo[] pis = t.GetProperties();
foreach (System.Reflection.PropertyInfo pi in pis)
{
DataColumn dc = new DataColumn(pi.Name, pi.PropertyType);
dt.Columns.Add(dc);
}
return ds;
}
public static DataSet FillDataSet(DataSet ds, object[] objArr)
{
DataColumnCollection dcs = ds.Tables[0].Columns;
Type t = objArr[0].GetType();
foreach (object obj in objArr)
{
DataRow dr = ds.Tables[0].NewRow();
for (int i = 0; i < dcs.Count; i++)
{
dr[i] = t.InvokeMember(dcs[i].ColumnName, System.Reflection.BindingFlags.GetProperty, null, obj, null);
}
ds.Tables[0].Rows.Add(dr);
}
return ds;
}