- 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 WebApplication2
- {
- public partial class _Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- var list = new List<Demo> {
- new Demo{ id=1,age=18, name="Tim"},
- new Demo{ id=2,age=22, name="Allen"},
- new Demo{ id=3,age=24, name="Jim"}
- };
- var ds = list.ToDataSet();
- GridView1.DataSource = ds.Tables[0];
- GridView1.DataBind();
- }
- }
- }
- static class Extensions
- {
- 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;
- }
- }
- class Demo
- {
- public int id { get; set; }
- public string name { get; set; }
- public int age { get; set; }
- }
- }
List转换成DataSet
最新推荐文章于 2021-02-13 04:03:20 发布
本文介绍了一种将C#中的对象列表转换为DataSet的方法,并通过一个具体示例展示了如何实现这一转换过程。该方法适用于ASP.NET Web应用程序中数据展示的需求。
1268

被折叠的 条评论
为什么被折叠?



