Wednesday 11 March 2015

Select Option Sorting

List is an ordered collection of elements which can be of any data type - primitive types, collections, sObjects, that are distinguished by their indices.

First element indices in List is always 0.

we can sort the list using sort() method. For primitive data type sorting is always done in ascending order.

example :
List<String> names = new List<String>{ 'Pawan','Vishal','Vivek','Rishabh','Dinda', 'pawan'};
system.debug(' List before Sorting : ' + names);
names.sort();
system.debug(' List after Sorting : ' + names);


sorted list will be
(Dinda, Pawan, Rishabh, Vishal, Vivek, pawan)
 
 
 




SelectOption is also sorts in ascending order using value and label fields  in sequence

1. The value of fields is used for sorting.
2. If value of fields have the same value or both are empty then label is used.

NOTE: empty fields precede non-empty fields

example:

List<SelectOption> options = new List<SelectOption>();
options.add(new SelectOption('A','India'));
options.add(new SelectOption('C','Japan'));
options.add(new SelectOption('A','USA'));
options.add(new SelectOption('','China'));
System.debug('SelectOption Before sorting: ' + options);
options.sort();
System.debug('SelectOption After sorting: ' + options);



Before sorting: (System.SelectOption[value="A", label="India", disabled="false"], 
                 System.SelectOption[value="C", label="Japan", disabled="false"], 
                 System.SelectOption[value="A", label="USA", disabled="false"], 
                 System.SelectOption[value="", label="China", disabled="false"])


After sorting: (System.SelectOption[value="", label="China", disabled="false"], 
                System.SelectOption[value="A", label="India", disabled="false"], 
                System.SelectOption[value="A", label="USA", disabled="false"], 
                System.SelectOption[value="C", label="Japan", disabled="false"])




No comments:

Post a Comment