List<T> 转换 DataTable

 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;       

  }    

}

原文地址:https://www.cnblogs.com/zhshlimi/p/4907139.html