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.CountryMasterselect new {country.CountryID,country.CountryName};
DataTable dt = LINQToDataTable(objEmpDataContext,vrCountry);
themhzPosted Jul 20, 2022, 10:46 AM
Good code thank you
Toan Dao KiemPosted Nov 9, 2017, 1:48 AM
Thanks. It work for me. DataClasses1DataContext db = new DataClasses1DataContext(); //dataGridView1.DataSource = db.BoxSelectAll(); //Call a storeprocedul DataTable dt = LINQToDataTable(db.DocumentSelectAll().ToList()); dataGridView1.DataSource = dataTableDoc;
vimal lakheraPosted Sep 18, 2014, 6:24 PM
Please feel free to use it
james gopinathPosted Jul 8, 2014, 6:24 AM
Hi VIMAL LAKHERA, Thanks for sharing this code.. Its very useful. I would like to use this code in my commercial application. can i use it? looking for license terms.. Thanks, Gopinath
Mukhtar AsaroriPosted Sep 23, 2012, 12:56 AM
Thanks, if I want to fill pageddatasource with all table data, Could you please help
minakshi rahateeditedPosted Aug 22, 2012, 4:56 AMEdited Aug 22, 2012, 5:00 AM
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);
shreekanth gaanjiPosted Oct 19, 2011, 1:49 AM
I used your first method.It works just fine.Thnaks alot for a wonderfull code sinppet.
Ray DexterPosted Sep 9, 2011, 3:34 AM
Great code, and very useful... Thks
jimmy kantesariaPosted Aug 18, 2011, 6:11 AM
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!!!!!!!!
Richa sharmaPosted Mar 14, 2011, 2:38 AM
i am using store procedure in linq when it convert query to IQueryable. it is null. but why?
Rajesh RoshanPosted Feb 5, 2011, 9:36 AM
very usefull code. Thanks Rajesh
knowledge DeedsPosted Nov 19, 2010, 4:27 AM
Thanks you guys for your comments. Mr. Vincent my god bless you and give you a nice heart in your next life
JohnPosted Sep 2, 2010, 11:45 AM
Thanks for the article. The LINQToDataTable function has been very helpful!
Ara YeritsianPosted May 6, 2010, 9:06 AM
I think those functions most be included in .net freamwork.
Ara YeritsianPosted May 6, 2010, 9:02 AM
Thanks for those ready to use functions.
Vivek MenonPosted Jul 6, 2009, 10:53 AM
Gr8 work... Saved me a lot of time!!
Bita FallahPosted May 31, 2009, 6:05 AM
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!!
Ryan EstandartePosted Mar 23, 2009, 5:59 AM
Hi there, Do you have any method where, instead of using IQueryable in sample 2, I can use ISingleResult?
Dimple PatelPosted Jan 5, 2009, 12:01 PM
public DataTable SqlLinqToDataTable(DataContext context, IQueryable queryResult) { DataTable table = new DataTable(); SqlCommand cmd = (SqlCommand)context.GetCommand(queryResult); new SqlDataAdapter(cmd).Fill(table); return table; }
VincenteditedPosted Oct 7, 2008, 7:45 AMEdited Oct 7, 2008, 7:46 AM
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