My earlier article on sorting child rows introduced a new method to the DataRow classes in a strongly typed DataSet, allowing us to retrieve a sorted array of the child rows of a given DataRow.

There's a problem with it, though - it turns out it's dog slow.

I did some very rudimentary profiling of the method by counting the number of system ticks it took to retrieve a sorted array of child rows 1000 times. I then wrote the same piece of code using a call to the Select() method on the child table, passing in the ID of the parent row as a filter.

My method: 6400 ticks on average.
Calling Select(): 150 ticks on average.

So there's no question that Select() is faster. Where does that leave us? Well, we need to revisit those methods:

public partial class CollectionDataSet
{
    public partial class AuthorsRow
    {
        public BooksRow[] GetBooksRows(bool sorted)
        {
            if (!sorted)
            {
                return GetBooksRows();
            }

            CollectionDataSet ds = (CollectionDataSet)Table.DataSet;

            return (BooksRow[])ds.Books.Select(
                String.Format("AuthorID = {0}", AuthorID), "PublishedDate");
        }
    }
}

(This assumes that 'AuthorID' is an int. The parameters to String.Format will look slightly different if the ID column is of a different type.)

So now we have a shorter method, which calls the Select method of the child table directly if the 'sorted' parameter is true. You'll note that we've used the row's Table property to get the DataSet that this row belongs to, in order to talk to the child table itself.

This is a much faster way to retrieve child rows than using the Array.Sort method, but it has one small drawback: The Select method can't sort on expressions. This means that if you wanted to sort the list on, say, "Parent(AuthorBooks).AuthorName" rather than "PublishedDate", you would have to introduce a new column to the Books table rather than simply passing that expression into the Select method.