Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a DataTable by filtering another DataTable

Tags:

.net

datatable

I'm working on a system that currently has a fairly complicated function that returns a DataTable, which it then binds to a GUI control on a ASP.NET WebForm.

My problem is that I need to filter the data returned - some of the data that is being returned should not be displayed to the user.

I'm aware of DataTable.select(), but that's not really what I need. First, it returns an array of DataRows, and I need a DataTable, so I can databind it to the GUI control. But more importantly, the filtering I need to do isn't something that can be easily put into a simple expression. I have an array of the elements which I do not want displayed, and I need to compare each element from the DataTable against that array.

What I could do, of course, is to create a new DataTable, reading everything out of the original, adding to the new what is appropriate, then databinding the new to the GUI control. But that just seems wrong, somehow. In this case, the number of elements in the original DataTable aren't likely to be enough that copying them all in memory is going to cause too much trouble, but I'm wondering if there is another way.

Does the .NET DataTable have functionality that would allow me to filter via a callback function?

like image 911
Jeff Dege Avatar asked Dec 23 '10 19:12

Jeff Dege


1 Answers

Use the DataView.ToTable method:

DataTable sourceTable = ...
string filter = ...
string sort = ...
DataView view = new DataView(sourceTable, filter, sort, DataViewRowState.CurrentRows);
DataTable newTable = view.ToTable();

If you can't put your filtering logic in a filter expression, you can resort to Linq to DataSet:

var query = from row in sourceTable.AsEnumerable()
            where row.Field<int>("foo") > 42
            && row.Field<string>("bar") == "hello"
            && ...
            select r;

var newTable = query.AsDataView().ToTable();

Or, if you already have a method that implements the filtering:

bool FilterRow(DataRow row)
{
    ...
}

...

var newTable = sourceTable.AsEnumerable().Where(FilterRow).AsDataView().ToTable();
like image 167
Thomas Levesque Avatar answered Oct 01 '22 22:10

Thomas Levesque