c#net 怎么给一个entity类型的list 转换成dataset
展开全部
// 扩展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;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询