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
john dsouzajohn dsouza 

How to sort custom list in apex

I have a picklist defined in vf page and I have created a custom setting (Countries__c ) which has a field CountryCode__c .
so its like this
Australia  CA
India        IN
America   USA

when the visual force page loads I want the picklist values to be sorted but it is not happening.
public class someclass
{
private List<SelectOption> countryCodeList = new List<SelectOption>();


    //Holds the Country Code for the selected option

    public String selectedCountryCode {get; set;}

   }

public  List<SelectOption> getCountryCodes() 
   {
        if(countryCodeList.isEmpty())
        {
           
          for(Countries__c country :Countries__c.getAll().values())
          {

            countryCodeList.add(new SelectOption(country.CountryCode__c, country.Name));
          }

        }

        countryCodeList.sort();  //doesnt work
        return countryCodeList;
   }
Please help me out.

Thanks
John
 
ManojjenaManojjena
HI John,

Try with below code !!
 
public  List<SelectOption> getCountryCodes(){
	if(countryCodeList.isEmpty()){
		for(Countries__c country :Countries__c.getAll().values().sort()){
			countryCodeList.add(new SelectOption(country.CountryCode__c, country.Name));
		}
	}
	return countryCodeList;
}
Let me know if it helps!!
Thanks
Manoj
 
john dsouzajohn dsouza
Hi

I am getting an error as  Loop must iterate over a collection type:

Thanks
John
ManojjenaManojjena
Hi John,

Try with below code it will work !!
public class someclass{
	private List<SelectOption> countryCodeList = new List<SelectOption>();
	//Holds the Country Code for the selected option
	public String selectedCountryCode {get; set;}
	public  List<SelectOption> getCountryCodes(){
		if(countryCodeList.isEmpty()){
		    List<Countries__c> countryLst=Countries__c.getAll().values();
			countryLst.sort();
			for(Countries__c country :countryLst){
				countryCodeList.add(new SelectOption(country.CountryCode__c, country.Name));
			}
		}
		countryCodeList.sort();  //doesnt work
		return countryCodeList;
	}
}

Let me know if it helps !!
Thanks 
Manoj