Sunday, 22 August 2010

AX - How to use Set and SetEnumerator

The Set class is used for the storage and retrieval of data from a collection in which the values of the elements contained are unique and serve as the key values according to which the data is automatically ordered.
You can create a set of primitive data types or complex data types such as a Class, Record or Container. Below is sample of a set of records.
static void _Set(Args _args)
{
    CustTable       custTable;
    Set             set = new Set(Types::Record);
    SetEnumerator   setEnumerator;
    ;

    while select custTable
    {
        if (custTable && !set.in(custTable))
        {
            set.add(custTable);
        }
    }

    if (!set.empty())
    {
        setEnumerator = set.getEnumerator();
        setEnumerator.reset();
        while (setEnumerator.moveNext())
        {
            custTable = setEnumerator.current();
            info(strfmt("Customer: %1",custTable.AccountNum));
        }
    }
}

Common mistake when creating a set of recIds is using integer. AX2009 uses Int64 but a cleaner way to write it is:
set = new Set(typeId2Type(typeid(recId)));

References:
http://msdn.microsoft.com/en-us/library/aa861938.aspx
http://msdn.microsoft.com/en-us/library/aa891129.aspx

No comments: