ARTICLE

Convert a LINQ Query Resultset to a DataTable

Posted by VIMAL LAKHERA Articles | LINQ June 24, 2008
After a long struggle I find out the way to convert a Linq Query resultset to DataTable object. The attached source code shows how to do it.
Reader Level:

After a long struggle I find out the way to convert  a Linq Query resultset to DataTable object. The attached source code shows how to do it. I am sharing this article with my developer friends and make their life easier.

Here are two samples.

Sample I:

I created a public method called LINQToDataTable as following:

public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
     DataTable dtReturn = new DataTable();

     // column names 
     PropertyInfo[] oProps = null;

     if (varlist == null) return dtReturn;

     foreach (T rec in varlist)
     {
          // Use reflection to get property names, to create table, Only first time, others 
          will follow 
          if (oProps == null)
          {
               oProps = ((
Type)rec.GetType()).GetProperties();
               foreach (PropertyInfo pi in oProps)
               {
                    Type colType = pi.PropertyType;

                    if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()      
                    ==typeof(Nullable<>)))
                     {
                         colType = colType.GetGenericArguments()[0];
                     }

                    dtReturn.Columns.Add(
new DataColumn(pi.Name, colType));
               }
          }

          DataRow dr = dtReturn.NewRow();

          foreach (PropertyInfo pi in oProps)
          {
               dr[pi.Name] = pi.GetValue(rec,
null) == null ?DBNull.Value :pi.GetValue
               (rec,null);
          }

          dtReturn.Rows.Add(dr);
     }
     return dtReturn;
}

---------------------------------------------------------------

Example: To use this method, just use the following code sample:

---------------------------------------------------------------

var vrCountry = from country in objEmpDataContext.CountryMaster
                        select new {country.CountryID,country.CountryName};

DataTable dt = LINQToDataTable(vrCountry);

Sample II

Here is my second method:

public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
{
     if (query == null)
     {
          throw new ArgumentNullException("query");
     }
     
    
IDbCommand
cmd = ctx.GetCommand(query as IQueryable);
     SqlDataAdapter adapter = new SqlDataAdapter();
     adapter.SelectCommand = (
SqlCommand)cmd;
     DataTable dt = new DataTable("sd");

     try
     {
          cmd.Connection.Open();
          adapter.FillSchema(dt,
SchemaType.Source); 
          adapter.Fill(dt);
     }
     finally
     {
          cmd.Connection.Close();
     }
     return dt;
}

---------------------------------------------------------------

Example: To use this method, just use the following code sample:

---------------------------------------------------------------

var vrCountry = from country in objEmpDataContext.CountryMaster
                        select new {country.CountryID,country.CountryName};

DataTable dt = LINQToDataTable(objEmpDataContext,vrCountry);

Login to add your contents and source code to this article
post comment
     

Thanks, if I want to fill pageddatasource with all table data, Could you please help

Posted by Mukhtar Asarori Sep 23, 2012

I got following error "Specified cast is not valid." my code is var groupbySort = from row in processNewData.AsEnumerable() group row by new { DueDate = row.Field<DateTime>("Duedate"), Familycode = row.Field<string>("Familycode") } into grp select new { Familycode=grp.Key.Familycode, DueDate=grp.Key.DueDate, PremiumSum=grp.Sum(r=>r.Field<decimal>("Premium")) }; DataTable output1 = LINQToDataTable(groupbySort);

Posted by minakshi rahate Aug 22, 2012

I used your first method.It works just fine.Thnaks alot for a wonderfull code sinppet.

Posted by shreekanth gaanji Oct 19, 2011

Great code, and very useful... Thks

Posted by Ray Dexter Sep 09, 2011

Hi, there i m using your sample II example code. I m getting this error : Value cannot be null. Parameter name: query when i debug it line by line error comes at line IDbCommand cmd = ctx.GetCommand(query as IQueryable); here is my code.....as i have done some modification in there: public DataTable ToDataTable(System.Data.Linq.DataContext ctx, int id) { DataClasses1DataContext objData = new DataClasses1DataContext(); var q = from s in objData.employees where s.id == id select s; object query = new object(); query = q.ToList(); if (query == null) { throw new ArgumentNullException("query"); } IDbCommand cmd = ctx.GetCommand(query as IQueryable); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = (SqlCommand)cmd; DataTable dt = new DataTable("sd"); try { cmd.Connection.Open(); adapter.FillSchema(dt, SchemaType.Source); adapter.Fill(dt); } finally { cmd.Connection.Close(); } return dt; } and here is the way i call function: DataClasses1DataContext db = new DataClasses1DataContext(); DataTable dt = new DataTable(); dt = ToDataTable(db, Convert.ToInt32(e.CommandArgument.ToString())); please help!!!!!!!!

Posted by jimmy kantesaria Aug 18, 2011
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.