Filter DataTable with LINQ

By Peter Bromberg

LINQ can be used to filter and order a DataTable. Here's an example

       // Need references to System.Linq and System.Data.DataSetExtensions  

         // first get our DataSet from Cache
         DataSet ds = (DataSet) Cache["threads"];
           // Get the datatable to work with
           DataTable dt = ds.Tables[0];
           // Use the .AsEnumerable extension method to make DataTable LINQ-friendly
            var results = from myRow in dt.AsEnumerable()
                            where myRow.Field<string>("Topic").Contains(this.txtSearch.Text)
                          select myRow;
             // Clone the original datatable as the results does not make easy access to column / schema info.
           DataTable dt2 = dt.Clone();
           DataRow row = null;
            // add the results items into the cloned DataTable
            foreach (var r in results)
            {
                row = dt2.NewRow();
                 row.ItemArray = r.ItemArray;
                 dt2.Rows.Add(row);
            }
            // bind the results to a GridView
            this.GridView1.DataSource = dt2;
             GridView1.DataBind();

Filter DataTable with LINQ  (2883 Views)