Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass DataTable.Select() result to a new DataTable?

Tags:

c#

.net

datatable

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?

like image 866
shajan Avatar asked Feb 03 '11 07:02

shajan


People also ask

Can we use linq to query against a DataTable?

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.

Which method creates a DataTable from an existing one and includes the data?

DataView.ToTable Method (System.Data) Creates and returns a new DataTable based on rows in an existing DataView.

How return DataTable from linq?

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.


2 Answers

You can use CopyToDataTable, available on IEnumerable<DataRow> types.

var filteredData = dt2.Select(expression).CopyToDataTable(); 
like image 188
Alex Bagnolini Avatar answered Sep 19 '22 12:09

Alex Bagnolini


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(); 
like image 36
mmcfly Avatar answered Sep 19 '22 12:09

mmcfly