With Salesforce's Apex, is there any way to sort list items, for Date field value. Please refer the TODO section of the following code, thanks.
/**
* Select list of jobOccurrences belongs to particular list of jobs
*/
private List<Job_Occurrence__c> getJobsByJobCode(List<Job__c> jobList) {
// Select relevant Job Occurrence objects
List<Job_Occurrence__c> jobOccuList = new List<Job_Occurrence__c>();
for (Job__c job : jobList) {
Job_Occurrence__c jobOccurrence = [SELECT Id, Job__c,
Schedule_Start_Date__c
FROM Job_Occurrence__c
WHERE Job__c =: job.Id];
if((jobOccurrence != null) && (jobOccurrence.Id != null)) {
jobOccuList.add(jobOccurrence);
}
}
if((jobOccuList != null) && (jobOccuList.size() > 0)) {
// TODO
// How I sort the 'jobOccuList' with Date field 'Schedule_Start_Date__c',
// for select the items according to sequence of latest jobOccurrence
return jobOccuList;
} else {
throw new RecordNotFoundException ('Could not found any jobOccurrence for given list of jobs');
}
}
You really should bulkify this code, i.e. not run a query inside a loop which could cause potentially cause issues with the governor limits, and since you just want the combined list for all
Job__c
records this makes your ordering easy too — you can do it in the query!The code you want to change is this:
Essentially we can optimise this to not only use one query instead of N (where N is
jobList.size()
) and get them ordered at the same time. First we need to gather the list of Job__c IDs, and then we can use theIN
statement in theWHERE
clause of the SOQL:Finally, if you need to be able to easily map back from the Job_Occurrence_c records to Job_c records, you could replace the set with a map as below, though given that you just want this list I don't think it's needed here (just providing it for completeness).
All of this code has been written in browser, so there may be some syntax errors but it should be good!
You can try :
It's working for me.
Cheers