ConvertToDataTable

 

  1. // T is a generic class  
  2. static DataTable ConvertToDataTable<T>(List<T> models)  
  3. {  
  4.     // creating a data table instance and typed it as our incoming model   
  5.     // as I make it generic, if you want, you can make it the model typed you want.  
  6.     DataTable dataTable = new DataTable(typeof(T).Name);  
  7.   
  8.     //Get all the properties of that model  
  9.     PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  10.   
  11.     // Loop through all the properties              
  12.     // Adding Column name to our datatable  
  13.     foreach (PropertyInfo prop in Props)  
  14.     {  
  15.         //Setting column names as Property names    
  16.         dataTable.Columns.Add(prop.Name);  
  17.     }  
  18.     // Adding Row and its value to our dataTable  
  19.     foreach (T item in models)  
  20.     {  
  21.         var values = new object[Props.Length];  
  22.         for (int i = 0; i < Props.Length; i++)  
  23.         {  
  24.             //inserting property values to datatable rows    
  25.             values[i] = Props[i].GetValue(item, null);  
  26.         }  
  27.         // Finally add value to datatable    
  28.         dataTable.Rows.Add(values);  
  29.     }  
  30.     return dataTable;  
  31. }  

Comments

Popular posts from this blog

Data Import Best Practices in Power BI

TRIGGER AUDIT TABLE SQL SERVER

Power BI Performance Tips and Techniques