C# .NET - IQueryable to DataTable - Asked By Zex on 25-May-10 09:19 AM

Is there option to convert from System.Linq.IQueryable to DataTable with some sort of ToDataTable() function, and avoid looping?
Sagar P replied to Zex on 25-May-10 10:34 AM
Try this for Without LOOP;

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

http://www.c-sharpcorner.com/UploadFile/VIMAL.LAKHERA/LINQResultsetToDatatable06242008042629AM/LINQResultsetToDatatable.aspx
Zex replied to Sagar P on 26-May-10 01:49 AM
Thank you, I tried this but It gives me similar speed performances as approach with loop (Sample I in http://www.c-sharpcorner.com/UploadFile/VIMAL.LAKHERA/LINQResultsetToDatatable06242008042629AM/LINQResultsetToDatatable.aspx). Actually I am wondering if there is something like http://msdn.microsoft.com/en-us/library/bb386921.aspx but with System.Linq.IQueryable instead IEnumerable? I have many functions that sends System.Linq.IQueryable parameters to this functions expecting DataRow[] on return.

Best Regards,
Zex