List转换成DataSet

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. namespace WebApplication2  
  9. {  
  10.     public partial class _Default : System.Web.UI.Page  
  11.     {  
  12.         protected void Page_Load(object sender, EventArgs e)  
  13.         {  
  14.             if (!IsPostBack)  
  15.             {  
  16.                 var list = new List<Demo> {  
  17.                     new Demo{ id=1,age=18, name="Tim"},  
  18.                     new Demo{ id=2,age=22, name="Allen"},  
  19.                     new Demo{ id=3,age=24, name="Jim"}  
  20.                 };  
  21.                 var ds = list.ToDataSet();  
  22.                 GridView1.DataSource = ds.Tables[0];  
  23.                 GridView1.DataBind();  
  24.             }  
  25.         }  
  26.     }  
  27.   
  28.     static class Extensions  
  29.     {  
  30.         internal static DataSet ToDataSet<T>(this IList<T> list)  
  31.         {  
  32.             Type elementType = typeof(T);  
  33.             var ds = new DataSet();  
  34.             var t = new DataTable();  
  35.             ds.Tables.Add(t);  
  36.             elementType.GetProperties().ToList().ForEach(propInfo => t.Columns.Add(propInfo.Name, Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType));  
  37.             foreach (T item in list)  
  38.             {  
  39.                 var row = t.NewRow();  
  40.                 elementType.GetProperties().ToList().ForEach(propInfo => row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value);  
  41.                 t.Rows.Add(row);  
  42.             }   
  43.             return ds;  
  44.         }  
  45.     }  
  46.     class Demo  
  47.     {  
  48.         public int id { getset; }  
  49.         public string name { getset; }  
  50.         public int age { getset; }  
  51.     }  
  52. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值