65.9K
CodeProject is changing. Read more.
Home

Convert Linq Query Result To DataTable

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (3 votes)

Apr 5, 2010

CPOL
viewsIcon

43370

Sometimes you need the Linq query result as datatable (I need it today)Use this: public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query) { if (query == null) { throw new ArgumentNullException("query"); ...

Sometimes you need the Linq query result as datatable (I need it today) Use this:
public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }
            IDbCommand cmd = ctx.GetCommand((IQueryable)query);
            System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter();
            adapter.SelectCommand = (System.Data.SqlClient.SqlCommand)cmd;
            DataTable dt = new DataTable("dataTbl");
            try
            {
                cmd.Connection.Open();
                adapter.FillSchema(dt, SchemaType.Source);
                adapter.Fill(dt);
            }
            finally
            {
                cmd.Connection.Close();
            }
            return dt;
        }
P.S.: I'm not the writer of this code, I just Googled it some time ago.