Tuesday, May 28, 2024

Sort X++ Map into a List

 Maps are auto sorted based on the key. Sometimes it might be required to get these values sorted and retrieved in a particular order. 

Below is a code snippet where a map is sorted and stored in a List where it can be retrieved in a sequential manner. The sorting of the map elements is done based on the value of each item, but the list is populated with the keys. 

       

	//Sorting of the values
        //add the sorted map values into a list
        mapEnumeratorParent = resourceWeights.getEnumerator();
        resourceList = new List( Types::String );
        
        while ( mapEnumeratorParent.moveNext() )        //iteration 1
        {           
            lowestResource = mapEnumeratorParent.currentKey();
            lowestWeight = mapEnumeratorParent.currentValue();

            mapEnumerator = resourceWeights.getEnumerator();
            while ( mapEnumerator.moveNext() )      //iteration 2
            {
                if ( mapEnumerator.currentValue() < lowestWeight )
                {
                    lowestResource = mapEnumerator.currentKey();
                    lowestWeight = mapEnumerator.currentValue();
                }
            }

            resourceList.addEnd( lowestResource);

            resourceWeights.remove( lowestResource ) ;
            mapEnumeratorParent = resourceWeights.getEnumerator();
        }