List转换成DataSet实现代码
程序员文章站
2023-12-10 22:55:34
复制代码 代码如下: /// /// list转换成dataset /// ///
/// <summary>
/// list转换成dataset
/// </summary>
/// <typeparam name="t">类型</typeparam>
/// <param name="list">将要转换的list</param>
/// <returns></returns>
public dataset converttodataset<t>(ilist<t> list)
{
if (list == null || list.count <= 0)
{
return null;
}
dataset ds = new dataset();
datatable dt = new datatable(typeof(t).name);
datacolumn column;
datarow row;
system.reflection.propertyinfo[] mypropertyinfo = typeof(t).getproperties(system.reflection.bindingflags.public | system.reflection.bindingflags.instance);
foreach (t t in list)
{
if (t == null)
{
continue;
}
row = dt.newrow();
for (int i = 0, j = mypropertyinfo.length; i < j; i++)
{
system.reflection.propertyinfo pi = mypropertyinfo[i];
string name = pi.name;
if (dt.columns[name] == null)
{
column = new datacolumn(name, pi.propertytype);
dt.columns.add(column);
}
row[name] = pi.getvalue(t, null);
}
dt.rows.add(row);
}
ds.tables.add(dt);
return ds;
}
复制代码 代码如下:
/// <summary>
/// list转换成dataset
/// </summary>
/// <typeparam name="t">类型</typeparam>
/// <param name="list">将要转换的list</param>
/// <returns></returns>
public dataset converttodataset<t>(ilist<t> list)
{
if (list == null || list.count <= 0)
{
return null;
}
dataset ds = new dataset();
datatable dt = new datatable(typeof(t).name);
datacolumn column;
datarow row;
system.reflection.propertyinfo[] mypropertyinfo = typeof(t).getproperties(system.reflection.bindingflags.public | system.reflection.bindingflags.instance);
foreach (t t in list)
{
if (t == null)
{
continue;
}
row = dt.newrow();
for (int i = 0, j = mypropertyinfo.length; i < j; i++)
{
system.reflection.propertyinfo pi = mypropertyinfo[i];
string name = pi.name;
if (dt.columns[name] == null)
{
column = new datacolumn(name, pi.propertytype);
dt.columns.add(column);
}
row[name] = pi.getvalue(t, null);
}
dt.rows.add(row);
}
ds.tables.add(dt);
return ds;
}