Map in D365 F&O - X++ Code

 Map in D365 F&O - X++ Code

  • The Map class lets to associate one value (the key) with another value.
  • Both the key and the 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.
  • Multiple keys can map to the same value, but one key can map to only one value at a time. If you add a (key, value) pair that has an existing key value, it replaces the existing pair with that key value.
  • The (key, value) pairs in a map can be traversed by using the MapEnumerator class.
<span style="font-family: Calibri;">
static void MapExample(Args _args)
{
    Map map = new Map(Types::String, Types::Integer);
    
    // Adding values to the map
    map.insert("John", 25);
    map.insert("Alice", 30);
    map.insert("Bob", 35);
    
    // Accessing values in the map
    int johnsAge = map.lookup("John");
    int alicesAge = map.lookup("Alice");
    
    info(strFmt("John's age: %1", johnsAge));
    info(strFmt("Alice's age: %1", alicesAge));
    
    // Updating a value in the map
    map.insert("Bob", 40);
    
    // Removing a key-value pair from the map
    map.remove("Alice");
    
    // Iterating through the map
    MapEnumerator enumerator = map.getEnumerator();
    
    while (enumerator.moveNext())
    {
        str name = enumerator.currentKey();
        int age = enumerator.currentValue();
        
        info(strFmt("%1's age: %2", name, age));
    }
}

</span>

Output:

<span style="font-family: Calibri;">
John's age: 25
Bob's age: 40
Alice's age: 30
John's age: 25</span>

Comments