Activity Forums Salesforce® Discussions How can I Sort Wrapper list in Salesforce?

  • PRANAV

    Member
    September 8, 2016 at 2:24 pm

    Hi All,

    How can I Sort Wrapper list?

    I have made a wrapper class in which there is a list of searched products, I want to display those searched result in ascending order of their name.

    Thanks

  • Mohit

    Member
    September 16, 2016 at 6:45 am

    Hi Pranav,

    Here is the code for sorting the wrapper list:-

    global class Book implements Comparable {

    public String BookTitle ;
    public String Author ;
    public Integer TotalPages ;
    public Double Price ;
    public Date publishingDate;

    public enum SORT_BY {
    ByTitle,ByPage
    }

    //Variable to decide the member on which sorting should be performed
    public static SORT_BY sortBy = SORT_BY.ByTitle;

    public Book(String bt, String a, Integer tp, Double p, Date pd)
    {
    BookTitle = bt;
    Author = a;
    TotalPages = tp;
    Price = p;
    publishingDate = pd;
    }

    global Integer compareTo(Object objToCompare) {
    //Sort by BookName Alphabetically
    if(sortBy == SORT_BY.ByTitle)
    {
    return BookTitle.compareTo(((Book)objToCompare).BookTitle);
    }
    else //Sort by Book price
    {
    return Integer.valueOf(Price - ((Book)objToCompare).Price);
    }
    }
    }

  • shariq

    Member
    September 19, 2018 at 1:13 pm

    Hi,

    You can use the sort() method of Salesforce List class.

    sort() :
    Sorts the items in the list in ascending order.

    Thanks

  • Parul

    Member
    September 22, 2018 at 5:25 am

    Adding some points and code snippet:

    37down vote
    Apex provides a sort method on the List class for sorting. For objects such as this however, you must implement the Comparable interface. Note the Salesforce doc samples indicate you need to make your class 'global' scope, this is no longer true.

    public class jobsWrapper implements Comparable
    {
    public Integer compareTo(Object compareTo)
    {
    jobsWrapper jobsWrapper = (jobsWrapper) compareTo;
    if (job.Name == jobsWrapper.job.Name) return 0;
    if (job.Name > jobsWrapper.job.Name) return 1;
    return -1;
    }
    }
    Then once you put your objects into a list you can use the sort method.

    List<jobsWrapper> jobs = new List<jobsWrapper>();
    // Add things to the list ...
    jobs.sort();

     

    Thanks

Viewing 1 - 4 of 4 posts

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos