首页 > 其他 > 详细

List<T> 转换 DataTable

时间:2015-10-24 17:27:54      阅读:261      评论:0      收藏:0      [点我收藏+]

 public class List2DataTable     {        

public static string GetClassName(Type type)     

    {             if (type == null)            

     throw new ArgumentException("参数type不能为空");

           if (type.HasAttribute<AliasAttribute>())   

  return type.GetAttribute<AliasAttribute>().Name.ToLower();        

     else      

       return type.Name.ToLower();      

   }        

public static DataTable ListToDataTable<T>(List<T> oList) where T : class    

     {          

   try          

   {               

  string tableName = GetClassName(typeof(T));       

          DataTable dt = new DataTable();                  

            string fieldName;             

     object fieldValue;              

   string[] fieldNames;             

               System.Reflection.PropertyInfo[] Props = typeof(T).GetProperties();   

              fieldNames = new string[Props.Length];          

for (int i = 0; i < Props.Length; i++)              

   {                 

    fieldName = Props[i].Name;          

           fieldNames[i] = fieldName;            

         dt.Columns.Add(fieldName, Props[i].PropertyType);    

             }             

    for (int r = 0; r < oList.Count; r++)            

     {                 

    DataRow dr = dt.NewRow();     

                T o = oList[r];             

        for (int i = 0; i < fieldNames.Length; i++)     

                {                    

     fieldValue = Props[i].GetValue(o, null);        

                 dr[fieldNames[i]] = fieldValue;       

              }                  

   dt.Rows.Add(dr);     

            }               

  return dt;            

}            

catch(Exception ex)             {             }     

        return null;       

  }    

}

List<T> 转换 DataTable

原文:http://www.cnblogs.com/zhshlimi/p/4907139.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!