Using RecordSortedList in Dynamics AX 2012

Dynamics AX 2012 has a nice class called RecordSortedList, which can be used to create a list of records from a database table. It can be useful when you need to pass a list of records into a method, or return a list of records from a method.

I honestly haven’t used it that often, but I had a case today where I thought it would be perfect. I had a method that currently returns a single record from a table, but that needed to be changed to return a short list of records.

I wrote some code to insert records into the list, then another bit to loop through the list and do something with the records in it. I was puzzled that, while I was definitely inserting multiple records into the list, I was only getting a single record back out. After some trial and error, I discovered that the methods to retrieve records from the list don’t really work right if you fail to explicitly set a sort order on the list. I wasn’t really concerned with sort order, so I didn’t bother setting one at first. Once I set a sort order, everything worked fine.

If you want to see this quirk for yourself, run the test job below with and without the sortOrder() call. As far as I can tell, this isn’t actually documented anywhere, so I thought I’d write up this blog post, as a reminder for myself, and as a resource for anyone else who happens to stumble across this little quirk.

/andyhuey/84495f8a3480d2df31f9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
static void AjhTestRSL(Args _args)
{
    CustTable custTable;
    RecordSortedList myList = new RecordSortedList(tableNum(CustTable));
    boolean moreRecs;
 
    myList.sortOrder(fieldNum(CustTable, AccountNum));
 
    // create a list
    while select firstOnly10 * from custTable
    {
        myList.ins(custTable);
    }
 
    // step through the list
    moreRecs = myList.first(custTable);
    while (moreRecs)
    {
        info(custTable.AccountNum);
        moreRecs = myList.next(custTable);
    }
}

3 Comments


  1. Not only this, but if you put a WRONG sort field in, such as a bad fieldId, it causes everything to fail similarly with no warnings. MAJOR design flaw I think.

    Reply

  2. If you don’t want a sort order and you just want it to loop through the records in the order that you inserted them, what do you do?

    Reply

  3. The sort order also serves as primary key for the list.So if you use a field or fields that may duplicate. You may miss some record(s). Try it.

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.