tags:

views:

1047

answers:

1

I have typed dataset with 1:N relationship between two tables. Child table has 'Order' column, that I use for sorting (ordery by) in SP when loading data into dataset. As I understand, this order is not guaranteed when working with dataset. I need GetChildRows of parent row and ensure that rows are in specific order defined in order column. Now I do following:

class Program
{
    static void Main(string[] args)
    {
        DataSet1 ds = new DataSet1();
        //load data
        DataSet1.ParentTableRow parentRow = ds.ParentTable.FindByID(1);
        DataSet1.ChildTableRow[] childRows = parentRow.GetChildTableRows();
        Array.Sort<DataSet1.ChildTableRow>(childRows, new ChildTableCoparer());
        //Enumerate fields is right order
    }
}

public class ChildTableCoparer : IComparer<DataSet1.ChildTableRow>
{
    public int Compare(DataSet1.ChildTableRow x, DataSet1.ChildTableRow y)
    {
        if (x.Order > y.Order) return 1;
        if (x.Order < y.Order) return -1;
        return 0;
    }
}

Is there better way how to ensure order when using GetChildRows() ?

A: 

You could try sorting the child table before you select rows from it. This way hopefully the array will be pre-sorted when you select rows from it.

For example:

DataSet1 ds = new DataSet1();

//load data
DataSet1.ChildTable.SortExpression = "Order";

DataSet1.ParentTableRow parentRow = ds.ParentTable.FindByID(1);
DataSet1.ChildTableRow[] childRows = parentRow.GetChildTableRows();
Array.Sort<DataSet1.ChildTableRow>(childRows, new ChildTableCoparer());
//Enumerate fields is right order

Or alternatively, you could write a LINQ expression to sort the resulting array

Steve