Tuesday, October 25, 2005

Using the built-in searching features of the DataSet

Mohammad Azam posted Searching in the DataSet to save a Database trip showing a simple technique for searching a DataSet. As he said "Then I asked myself why not search the DataSet instead of going to the Database." however the technique he showed was a hand-crafted, walk the rows approach that compared the column value in each row and, if they matched, he copied the row into a new DataTable instance. In the end he'd have a DataTable containing the matching rows. He may not be aware that DataTables are searchable already via the DataTable.Select Method. Here's a snippet from the MSDN docs showing how it would work...

string strExpr;
string strSort;
strExpr = "id > 5";
// Sort descending by column named
CompanyName. strSort = "name DESC";
// Use the Select method to find all rows matching the filter.
DataRow[] foundRows = customerTable.Select( strExpr, strSort, DataViewRowState.Added );

Obviously, his example and my response both lack context of the problem being solved. If his goal was to return a DataTable then the array of DataRows isn't exactly what he needs. However, the search (filtering) technique is still valid for consideration even without context.

Original post

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.