I have a DataTable
named dt2
with data. I am calling its Select
method to get some specific rows.
DataRow[] foundRows; expression = "parent_id=1"; foundRows = dt2.Select(expression);
How can I pass the Select
-method result to a new DataTable
– say FilteredData
?
Can we use linq to query against a DataTable? Explanation: We cannot use query against the DataTable's Rows collection, since DataRowCollection doesn't implement IEnumerable<T>. We need to use the AsEnumerable() extension for DataTable.
DataView.ToTable Method (System.Data) Creates and returns a new DataTable based on rows in an existing DataView.
To query datatable using linq we call the AsEnumerable() method of the DataTable. Calling this method on the DataTable returns an object which implements the IEnumerable<T> interface. Now we can perform LINQ queries on this object. Add a reference to the System.
You can use CopyToDataTable
, available on IEnumerable<DataRow>
types.
var filteredData = dt2.Select(expression).CopyToDataTable();
Just for clarity, the Select
method returns an array of type DataRow
. That's why we need to use CopyToDataTable()
. Alex's answer is good. However, if the Select
didn't return any rows, CopyToDataTable()
will throw an InvalidOperationException
.
So test that there is at least one DataRow
before using the CopyToDataTable()
.
var filteredDataRows = dt2.Select(expression); var filteredDataTable = new DataTable(); if(filteredDataRows.Length != 0) filteredDataTable = filteredDataRows.CopyToDataTable();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With