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
Don Schueler 18Don Schueler 18 

Sort sObject List with multiple sObject types on CreatedDate

I am doing this...all is well except that I need to sort on CreatedDate. Is there a simple approach?

List<sObject> objects = new List<sObject>();
objects.addAll((List<sObject>)(accountList));
objects.addAll((List<sObject>)(contactList));
Raj VakatiRaj Vakati

To implement a custom sort order for sObjects in lists, create a wrapper class for the sObject and implement the Comparable interface. The wrapper class contains the sObject in question and implements the compareTo method, in which you specify the sort logic.



https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_list_sorting_sobject.htm
Don Schueler 18Don Schueler 18
Raj, i get that part for a single sObject....but for some reason its not clear to me how I take my compoud  "object" which has multiple different sObjects in it into comparable.
Steven NsubugaSteven Nsubuga
Hi Dan, in short, there is no simple approach.
You would need to convert each generic SObject back to its true type, in order to access its CreatedDate. Sadly only the ID field is accessible via the generic SObject record.

Below is some code you can tinker with. 
public static void echoSobjectTypes(List<sObject> objects) {
        
        for (sObject obj : objects)
        {         
            System.debug('Object type is 'obj.getSObjectType() + ' and ID = '+ obj.Id);
            String objId = obj.Id;
            System.debug(database.query('SELECT CreatedDate FROM '+objType + ' WHERE Id = :objId'));
        } 
    }