AX Deleting items from a map

I faced a challenge in deleting specific items from a map today. The problem occurs when the recordIterator.delete() x++ statement is executed. Any consecutive statement using the recordIterator variable will throw the exception ‘the iterator does not designate a valid element’. According to SysDictCoder it is not a problem to remove items using the ListIterator though.

The solutions lays within the use of a set in which the keys of the items that needs to be deleted are stored. After the first iteration another iteration takes place to actually delete the applicable items from the map.

public Map cleanupRecordMap(Map _recordMap)
{
    MapIterator     recordIterator = new MapIterator(_recordMap);
    Set             deleteRecordSet = new Set(Types::String);
    SetEnumerator   deleteRecordSetEnumerator;
    ;

    if(_recordMap.elements() > 0)
    {
        while(recordIterator.more())
        {
            if(true)
            {
                // mark record to be deleted by adding it to a set
                deleteRecordSet.add(recordIterator.domainValue());
            }
            
            recordIterator.next();                                 
        }
                
        // use the set of keys to remove them from the map
        deleteRecordSetEnumerator = deleteRecordSet.getEnumerator();
        while(deleteRecordSetEnumerator.moveNext())
        {
            _recordMap.remove(deleteRecordSetEnumerator.current());   
        }
    }       

    return _recordMap;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>