using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace AppPhoneInfo
{
public partial class Home : System.Web.UI.Page
{
DBHelp.DBHelpDAL DBhelp = new DBHelp.DBHelpDAL();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
List<Model.Model> list = new List<Model.Model>();
list = DBhelp.GetPhoneList();
DataSet ds = list.ToDataSet();
}
}
public static class ToDataSetMethod//必須為靜態類
{
internal static DataSet ToDataSet<T>(this IList<T> list)
{
Type elementType = typeof(T);
var ds = new DataSet();
var t = new DataTable();
ds.Tables.Add(t);
elementType.GetProperties().ToList().ForEach(propInfo => t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));
foreach (T item in list)
{
var row = t.NewRow();
elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);
t.Rows.Add(row);
}
return ds;
}
}
}
.net list<T> 轉DataSet
最新推荐文章于 2023-06-12 22:01:26 发布