?
Solved

How to I custom sort multiple fields in SalesForce Apex

Posted on 2014-01-13
2
Medium Priority
?
852 Views
Last Modified: 2016-06-13
In a Salesforce Apex class how can we sort a list of custom objects by multiple fields asc or desc?  I have a need to sort based on certain conditions from within an apex trigger.  I cannot re-query the data to sort using a soql query because it hits a query limit.
 
I know half the answer to this question.  Create a wrapper class http://salesforce.stackexchange.com/questions/8370/how-to-sort-wrapper-list .  Just have to figure out how to do it for multiple fields.  Also, I’m hoping there is an easier way.
0
Comment
Question by:heykjo
1 Comment
 
LVL 1

Accepted Solution

by:
Jamie Browning earned 2000 total points
ID: 40144382
First of all I would establish your sorting rules.
Then rewrite something like this:

public class jobsWrapper implements Comparable
{
    public Integer compareTo(Object compareTo)
    {
        jobsWrapper jobsWrapper = (jobsWrapper) compareTo;
        if (job.Name == jobsWrapper.job.Name && job.Custom__c == jobsWrapper.job.Custom__c) return 0;
        if (job.Name == jobsWrapper.job.Name && job.Custom__c > jobsWrapper.job.Custom__c) return 1;
        if (job.Name == jobsWrapper.job.Name && job.Custom__c < jobsWrapper.job.Custom__c) return -1;
        if (job.Name > jobsWrapper.job.Name) return 1;
        return -1;        
    }
}
The Same as the code provided but has additional levels of Logic.
Not sure what limits you were previously hitting but this may at least give you a start.
To add further fields use the same pattern I have applied with and && logical and and further == , > , < expressions.

I hope this helps.
I can provide more if you need.

Jamie
1

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
Q&A with Course Creator, Mark Lassoff, on the importance of HTML5 in the career of a modern-day developer.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
Simple Linear Regression

750 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question