Share via


How to convert this LINQ Result to DataTable

Question

Thursday, April 30, 2015 3:10 AM

        static void Main(string[] args)
        {
            SchoolManagementEntities objSchoolManagementEntities = new SchoolManagementEntities();

            var query = from r in objSchoolManagementEntities.Students select r;
            DataTable dt;
        }

All replies (4)

Thursday, April 30, 2015 4:16 AM ✅Answered | 2 votes

For LINQ2DataSet, you could use the DataTableExtensions.CopyToDataTable Method to convert the LINQ query result to a DataTable directly.

Some information to get you started:

http://blogs.msdn.com/erickt/archive/2007/08/24/linq-to-dataset-data-binding.aspx

Rachit

Please mark as answer or vote as helpful if my reply does


Friday, May 1, 2015 2:46 AM ✅Answered | 1 vote

@VijayPrativadi,

Just do a little complement

LINQ to DataSet is to work with DataTable, and DataSet objects

You need to use the AsEnumerable() extension for DataTable. Like so:

            DataTable orders = ds.Tables["SalesOrderHeader"];

            // Query the SalesOrderHeader table for orders placed  
            // after August 8, 2001.
            IEnumerable<DataRow> query =
                from order in orders.AsEnumerable()
                where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
                select order;

DataTableExtensions.AsEnumerable Method returns IEnumerable<DataRow>. If you need to convert IEnumerable<DataRow> to a DataTable, use the CopyToDataTable() extension.

            // Create a table from the query.
            DataTable boundTable = query.CopyToDataTable<DataRow>();

Hope this will be helpful.

Have a nice day!

Kristin

We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.


Saturday, May 2, 2015 3:10 PM

Awesome @Rachit. Thanks 


Saturday, May 2, 2015 3:10 PM

Thanks Kristin!