Tuesday, 7 November 2017

How to convert linq query result in datatable


                         Follow Me To get Health and bodybuilding tip's
instagram:sayyedtanveer1410



LINQ stands for Language Integrated Query is a set of features introduced in Visual Studio 2008, using LINQ you can manipulate the data as similar SQL queries .Let us learn it practically how to convert LINQ query result to Datatable by creating one simple function.


Create function to named LINQResultQueryToDataTable which convert LINQ Result To DataTable as

public DataTable LINQResultQueryToDataTable<T>(IEnumerable<T> Linqlist) 
       { 
          
  1. DataTable dt = new DataTable();  
  2.   
  3.              
  4.             PropertyInfo[] columns = null;  
  5.   
  6.             if (Linqlist == nullreturn dt;  
  7.   
  8.             foreach (T Record in Linqlist)  
  9.             {  
  10.                   
  11.                 if (columns == null)  
  12.                 {  
  13.                     columns = ((Type)Record.GetType()).GetProperties();  
  14.                     foreach (PropertyInfo GetProperty in columns)  
  15.                     {  
  16.                         Type colType = GetProperty.PropertyType;  
  17.                              if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()  
  18.                         == typeof(Nullable<>)))  
  19.                         {  
  20.                             colType = colType.GetGenericArguments()[0];  
  21.                         }  
  22.   
  23.                         dt.Columns.Add(new DataColumn(GetProperty.Name, colType));  
  24.                     }  
  25.                 }  
  26.   
  27.                 DataRow dr = dt.NewRow();  
  28.   
  29.                 foreach (PropertyInfo pinfo in columns)  
  30.                 {  
  31.                     dr[pinfo.Name] = pinfo.GetValue(Record, null) == null ? DBNull.Value : pinfo.GetValue  
  32.                     (Record, null);  
  33.                 }  
  34.   
  35.                 dt.Rows.Add(dr);  
  36.             }  
  37.             return dt;  
  38.         }  
  39.   
       }  
The above function takes the LINQ query result and convert it into the Data Table

No comments:

Post a Comment