function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Abhinav GuptaAbhinav Gupta 

Sorting Apex SelectOption by Label or Value

Created a simple and easy to use API for sorting SelectOption collection by Label/Value. Not creating a codeshare project for it, as its a single class. All source code is available here : https://github.com/abhinavguptas/Apex-Select-Option-Sorting For more details, please check this post : http://www.tgerm.com/2011/08/salesforce-apex-selectoption-sort.html
James Kosharsky 2James Kosharsky 2
I'm sure Abhinav has a good option, but I found that it was easiest to just join the [label]+'@!@'+[value] in a list, sort the list and then seperate out the components to recreate the select option list.
 
public static List<SelectOption> sortSelectOptionList(List<SelectOption> source)
    {
        List<string> sortable = new  LIst<string>();
        for(SelectOption so: source)
        {
            // replace blank with '_!' so we know the final split will have two components
            sortable.Add((string.isblank(so.getLabel())?'_!':so.getLabel()) + '@!@' + (string.isblank(so.getValue())?'_!':so.getValue()));
        }
        // sort the list
        sortable.sort();
        List<SelectOption> targetList = new  List<SelectOption>();
        // split the value/name components and re create the list
        for(string s: sortable)
        {
                targetList.Add(new  SelectOption(s.split('@!@')[1].replace('_!',''), s.split('@!@')[0].replace('_!','')));
         
        }
        return targetList;
    }