34

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?

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
shajan
  • 341
  • 1
  • 3
  • 3

3 Answers3

69

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

var filteredData = dt2.Select(expression).CopyToDataTable();
Alex Bagnolini
  • 21,990
  • 3
  • 41
  • 41
19

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();
Community
  • 1
  • 1
mmcfly
  • 834
  • 8
  • 12
  • why use `var filteredDataRows` instead of `DataTable[] filteredDataRows`. your solution works great so I am just curious – Dave Hampel May 24 '20 at 01:41
  • @DaveHampel Use `var` when you are a bit lazy or for better oversight in the code, the variable names are aligned over each other. It means the same and compiles to the same and are indeed strongly typed. It's just not explicit. I normally use `var` when it's obvious from the assignment. I don't do `DataTable table = New DataTable();` but I do use `MyFancyClass mfc = SomeFunctionReturningAnMFC()` More info at https://intellitect.com/when-to-use-and-not-use-var-in-c/ and https://stackoverflow.com/a/4868500/1093940 – SvendK Jul 06 '20 at 18:22
16

Why not use a DataView instead?

DataView view = new DataView(dt2);
view.RowFilter = "parent_id = 1";

DataView will behave in very much the same way that a DataTable would with the added benefit that any change(s) to the underlying DataTable (dt2 in this case) would be automatically reflected in the DataView.

ardila
  • 1,277
  • 1
  • 13
  • 24