Отсортировать результат GetChildRows

Andrey Mamitko
Дата: 18.07.2005 12:06:00
У DataRow есть метод GetChildRows, который возврощает массив экземпляров класс DataRow (DataRow []).

Как его (этот массив) отсортировать по какому либо полю?

Спасибо.
buser
Дата: 27.07.2005 13:22:16
MSDN
Dialog Box: Sorting on Relations
In my application, I have a DataSet with two tables put into relation through a DataRelation object. I display the master table in a datagrid and then, when one row gets selected, I access the child records through GetChildRows. All this works fine, yet I have a problem. How can I retrieve the child rows in a sorted way? I tried setting the Sort property on the default view of the child table, but with no result.

I know the issue, but so far I've only been able to work around it. First of all, the problem magically disappears if you happen to get the child table already sorted. Unless you need to determine dynamically which column to sort by, the issue could be closed by simply appending an ORDER BY clause to your SQL query statement. (Incidentally, this brilliantly solved my instance of the problem.)

Another workaround consists of returning a sorted array to the control that actually displays the child rows. Whatever type they are made of, including DataRow objects, arrays can be sorted through a class that implements the IComparer interface. You call the static method Sort and specify the type-specific class. For example,

class DataRowComparer : IComparer
{
public int Compare(Object x, Object y)
{
DataRow drX = (DataRow) x;
DataRow drY = (DataRow) y;

return String.Compare(drX["column_name"].ToString(),
drY["column_name"].ToString());
}
}

To sort using this algorythm, do the following:

DataRow[] adr = dr.GetChildRows("relation_name");
DataRowComparer drc = new DataRowComparer();
Array.Sort(adr, drc);
foreach(DataRow tmp in adr)
{...}

In this way, the child rows will be enumerated according to the sort algorythm.

I repeatedly used the expression workaround here. There's a reason for this. The perfect solution for this kind of issue would be the DataViewManager object. You set the Sort property on a table specific view, set the DataViewManager object as the data source property of the list control, and tell to the DataMember property of the control to get data from the given table. It works, but so far only for Windows Forms datagrids.