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
Vijay Nagarathinam 41Vijay Nagarathinam 41 

Order By logic using APex

HI All,

I want to implement the order by logic using apex code. I will pass the list<sobject> records based on the single field I need to manipulate the order by logic. Please let me know if anyone has any suggestions.

Thanks,
Vijay
Raj VakatiRaj Vakati
You can able to sort using  Comparable 

Adds sorting support for Lists that contain non-primitive types, that is, Lists of user-defined types.

 
public abstract class Comparator {
    public abstract Integer compare(Object o1, Object o2);
    public static void sort(Object[] values, Comparator comp) {
        //  Obtain the list type of values
        Object[] temp = values.clone();
        temp.clear();
        //  Helper class for sorting using Comparable
        Helper[] tempValues = new Helper[0];
        for(Object value: values) {
            tempValues.add(new Helper(comp, value));
        }
        //  Perform sort
        tempValues.sort();
        //  Extract values back into temp list
        for(Helper helper: tempValues) {
            temp.add(helper.value);
        }
        //  And set the list to the new, sorted order
        values.clear();
        values.addAll(temp);
    }
    //  Simply calls Comparator when asked.
    class Helper implements Comparable {
        Comparator method;
        Object value;
        Helper(Comparator comp, Object val) {
            method = comp;
            value = val;
        }
        public Integer compareTo(Object o) {
            return method.compare(value, ((Helper)o).value);
        }
    }
}


Refer this links


https://developer.salesforce.com/forums/?id=906F0000000kAdoIAE
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_comparable.htm#apex_comparable
http://blog.deadlypenguin.com/blog/2015/10/10/comparable-sorting-objects-in-salesforce/
https://focusonforce.com/development/sorting-lists-in-salesforce/
https://salesforce.stackexchange.com/questions/68855/sorting-a-list-of-sobjects
https://thysmichels.com/2017/03/10/apex-sorting-objects-with-comparable-interface/