• 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;       

      }    

    }

  • 相关阅读:
    SNMP简介
    命令模式
    牛顿法
    仿射函数
    schedule
    命令模式
    牛顿法
    schedule
    仿射函数
    适配器模式
  • 原文地址:https://www.cnblogs.com/zhshlimi/p/4907139.html
Copyright © 2020-2023  润新知