.net list<T> 轉DataSet

来源:互联网 发布:ros绑定mac 编辑:程序博客网 时间:2024/06/06 17:24
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;        }    }}

0 0
原创粉丝点击