DataTable 和List 相互转换

        ///   <summary>
        
///  转换为一个DataTable
        
///   </summary>
        
///   <typeparam name="TResult"></typeparam>
        
///   <param name="value"></param>
        
///   <returns></returns>
         public   static  DataTable ToDataTable < TResult > ( this  IEnumerable < TResult >  value)  where  TResult :  class
        {
            
// 创建属性的集合
            List < PropertyInfo >  pList  =   new  List < PropertyInfo > ();
            
// 获得反射的入口
            Type type  =   typeof (TResult);
            DataTable dt 
=   new  DataTable();
            
// 把所有的public属性加入到集合 并添加DataTable的列
            Array.ForEach < PropertyInfo > (type.GetProperties(), p  =>  { pList.Add(p);dt.Columns.Add(p.Name, p.PropertyType); });      
            
foreach  (var item  in  value)
            {
                
// 创建一个DataRow实例
                DataRow row  =  dt.NewRow();
                
// 给row 赋值
                pList.ForEach(p  =>  row[p.Name]  =  p.GetValue(item,  null ));
                
// 加入到DataTable
                dt.Rows.Add(row);
            }
            
return  dt;
        }

    }

        /// <summary>
        
/// DataTable 转换为List 集合
        
/// </summary>
        
/// <typeparam name="TResult">类型</typeparam>
        
/// <param name="dt">DataTable</param>
        
/// <returns></returns>
        public static List<TResult> ToList<TResult>(this DataTable dt) where TResult : class,new()  
        {
            
//创建一个属性的列表
            List<PropertyInfo> prlist = new List<PropertyInfo>();
            
//获取TResult的类型实例  反射的入口
            Type t = typeof(TResult);
            
//获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表 
            Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -1) prlist.Add(p); });
            
//创建返回的集合
            List<TResult> oblist = new List<TResult>();
            
            
foreach (DataRow row in dt.Rows)
            {
                
//创建TResult的实例
                TResult ob = new TResult();
                
//找到对应的数据  并赋值
                prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
                
//放入到返回的集合中.
                oblist.Add(ob);
            }
            
return oblist;
        }

原文地址:http://www.cnblogs.com/chenliang0724/archive/2009/05/20/1471780.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值