码迷,mamicode.com
首页 > 其他好文 > 详细

List<T> 转换 DataTable

时间:2015-10-24 17:31:06      阅读:164      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!