Monday, April 2, 2018

Sorting Wrapper List in ASC or DESC order based on Wrapper Property

We get these kind of scenarios in which we have List of wrapper available and want to sort it either in ASC or DESC order based on any member variable wrapper class.

Suppose we have wrapper class as mentioned below:

public class SK_sortUtilityTestWrapper {
public string category{get;set;}
        public decimal count{get;set;}
    public SK_sortUtilityTestWrapper(string ss,decimal sk){
             this.category=ss;
             this.count=sk;
    }
}

Now imagine if we have list<SK_sortUtilityTestWrapper>  and want to sort list based on count value then we can do that by using below code.
I have added a static method which can be called from developer console to see the output for reference.



From developer console execute below script:

SK_WrapperSortUtility.testWrapperListSorting();

You will see below output in debug logs:


 Hope this will help!!!!


3 comments:

  1. Hi Friend,

    We should use comparable interface instead of writing our custom code handling all the stuffs.

    Reference : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_list_sorting_sobject.htm

    ReplyDelete
  2. Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. food ordering system

    ReplyDelete