Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » LINQ » Convert a LINQ Query Resultset to a DataTable

Convert a LINQ Query Resultset to a DataTable

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.

Page Views : 95204
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
VIMAL LAKHERA
Hi, I am working as a Team Lead in Synapse Communications pvt ltd for the last 1 and half year.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
You'd better do more search before you write code and publish article. by Vincent On October 7, 2008
The Linq2Dataset dll extension has already been included in net framework 3.5, I can't see why you need to create something to convert linq result to DataTable
Reply | Email | Modify 
Re: You'd better do more search before you write code and publish article. by Bita On May 31, 2009

is anything in .net framework 3.5 that convert query2sql resultset to dataset?!
could you tell how we could do that?

Reply | Email | Modify 
Re: You'd better do more search before you write code and publish article. by Brett On September 3, 2010
Your response sounded quite rude.

...and so how would you use Linq2Dataset to convert an IEnumerable<> to a DataTable?

Reply | Email | Modify 
Re: You'd better do more search before you write code and publish article. by knowledge On November 19, 2010

Dude, you sound uite rude.

If you have the solution with you then post it otherwise keep your mouth shut.

 

Reply | Email | Modify 
This could also work by Dimple On January 5, 2009
public DataTable SqlLinqToDataTable(DataContext context, IQueryable queryResult) { DataTable table = new DataTable(); SqlCommand cmd = (SqlCommand)context.GetCommand(queryResult); new SqlDataAdapter(cmd).Fill(table); return table; }
Reply | Email | Modify 
Method for stored procedures (ISingleResult) by Ryan On March 23, 2009
Hi there, Do you have any method where, instead of using IQueryable in sample 2, I can use ISingleResult?
Reply | Email | Modify 
thx for solution by Bita On May 31, 2009
thank you so much. it is 2 days that i've been searching for a solution which be able to fill a datatable with linq to query resultset.but couldn't find a workable and nice solution.
But don't you think that microsoft should predict and prevent it!!
Reply | Email | Modify 
Nice! by Vivek On July 6, 2009

Gr8 work... Saved me a lot of time!!

Reply | Email | Modify 
Thanks by Ara On May 6, 2010
Thanks for those ready to use functions.
Reply | Email | Modify 
Thanks by Ara On May 6, 2010
I think those functions most be included in .net freamwork.
Reply | Email | Modify 
Thanks! by John On September 2, 2010

Thanks for the article.  The LINQToDataTable function has been very helpful!

Reply | Email | Modify 
Thanks you guys for your comments by knowledge On November 19, 2010
Thanks you guys for your comments.
 Mr. Vincent my god bless you and give you a nice heart in your next life
Reply | Email | Modify 
About by Rajesh On February 5, 2011
very usefull code. Thanks Rajesh
Reply | Email | Modify 
Problem with code by Richa On March 14, 2011
i am using store procedure in linq when it convert query to IQueryable. it is null. but why?
Reply | Email | Modify 
Error by jimmy On August 18, 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!!!!!!!!
Reply | Email | Modify 
Thks for the code from JR by Ray On September 9, 2011
Great code, and very useful... Thks
Reply | Email | Modify 
Thank you by shreekanth On October 19, 2011
I used your first method.It works just fine.Thnaks alot for a wonderfull code sinppet.
Reply | Email | Modify 
Mindcracker MVP Summit 2012
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.