DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 21.4 Sorting Recordsets by a Single Column

21.4.1 Problem

You want to sort the records in a recordset, ordering them by the values in a single column.

21.4.2 Solution

Use the RecordSet.sortItemsBy( ) method.

21.4.3 Discussion

If you want to do a simple sort (sorting according to one column) on a recordset, use the sortItemsBy( ) method. This method takes the name of the column on which to sort as a parameter, and it sorts the records within the original recordset (no copy is made). Passing the value "DESC" to the method as a second parameter sorts the records in descending order. Otherwise, the sort order is ascending.

#include "NetServices.as"

rs = new RecordSet(["ID", "NAME"]);
rs.addItem({ID: 24, NAME: "a"});
rs.addItem({ID: 42, NAME: "b"});
rs.addItem({ID: 66, NAME: "c"});
rs.addItem({ID: 93, NAME: "d"});
rs.addItem({ID: 33, NAME: "e"});

// Sort the recordset by ID values in ascending order.
rs.sortItemsBy("ID");

/* Outputs:
   record 0
     ID: 24
     NAME: a
    record 1
     ID: 33
     NAME: e
   record 2
     ID: 42
     NAME: b
   record 3
     ID: 66
     NAME: c
   record 4
     ID: 93
     NAME: d
*/
rs.trace(  );

// Sort the recordset by the NAME column in descending order.
rs.sortItemsBy("NAME", "DESC");

/* Outputs:
   record 0
     ID: 33
     NAME: e
   record 1
     ID: 93
     NAME: d
   record 2
     ID: 66
     NAME: c
   record 3
     ID: 42
     NAME: b
   record 4
     ID: 24
     NAME: a
*/
rs.trace(  );
    [ Team LiB ] Previous Section Next Section