c#net 怎么给一个entity类型的list 转换成dataset
发布网友
发布时间:2023-07-18 09:32
我来回答
共1个回答
热心网友
时间:2024-12-12 21:58
// 扩展List集合
static class ExternList {
public static DataSet ToDataSet<TSource>(this IList<TSource> list)
{
Type elementType = typeof(TSource);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
foreach (var pi in elementType.GetProperties())
{
Type colType = Nullable.GetUnderlyingType(pi.PropertyType) ?? pi.PropertyType;
dt.Columns.Add(pi.Name, colType);
}
foreach (TSource item in list)
{
DataRow row = dt.NewRow();
foreach (var pi in elementType.GetProperties())
{
row[pi.Name] = pi.GetValue(item, null) ?? DBNull.Value;
}
dt.Rows.Add(row);
}
return ds;
}
}
// 调用示例:
public class YourType{
public string Name { get; set; }
}
IList<YourType> list = new List<YourType>{
new YourType(){Name="Foo1"},
new YourType(){Name="Foo2"},
new YourType(){Name="Foo3"}
};
DataSet ds = list.ToDataSet<YourType>();
DataTable dt = ds != null && ds.Tables.Count > 0 ? ds.Tables[0] : null;