D365FO – AX – How to use Map and MapEnumerator (X++)

Similar to Set class, Map class allows you to associate one value (the key) with another value. Both the key and value can be any valid X++ type, including objects. The types of the key and the value are specified in the declaration of the map. The way in which maps are implemented means that access to the values is very fast.
Below is a sample code that sets and retrieves values from a map.

static void checkItemNameAliasDuplicate(Args _args)
{
    inventTable         inventTable;
    Map                 map;
    MapEnumerator       mapEnumerator;
    NameAlias           nameAlias;
    int                 counter = 0;
    ;
    map = new Map(Types::String, Types::Integer);
    //If the second type is an object the "Types" value is Types::record
    //map = new Map(Types::String, Types::record);
    //store into map
    while select inventTable
    {
        nameAlias = inventTable.NameAlias;
        if (!map.exists(nameAlias))
        {
            map.insert(nameAlias, 1);
        }
        else
        {
            map.insert(nameAlias, map.lookup(nameAlias) + 1);
        }
    }
    //retrieve from map
    mapEnumerator = map.getEnumerator();
    while (mapEnumerator.moveNext())
    {
        nameAlias       = mapEnumerator.currentKey();
        info(strfmt("%1,%2",mapEnumerator.currentKey(),mapEnumerator.currentValue()));
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s