There are usually some requirements in the project that need to sort the list of data for a sobject to the foreground page, but the list above does not meet the complex functionality, which requires a custom comparison of two object sizes. So you need to create compare related classes to implement the comparable interface.
Requirements: The implementation of Goods__c list sorting, Goodsbrand__c for Huawei according to Price in ascending order, Goodsbrand__c for Lenovo in descending order of price.
1 PublicWithout sharingclassComparedgoodsImplementscomparable{2 Privategoods__c Goods{get;set;}3 4 Private Static FinalString Goods_brand_huawei = ' Huawei ';5 6 Private Static FinalString Goods_brand_lianxiang = ' Lenovo ';7 8 Publiccomparedgoods (Goods__c obj) {9Goods =obj;Ten } One A PublicInteger compareTo (Object objecttocompareto) { -Goods__c Comparedgoods =(Goods__c) Objecttocompareto; -Integer Comparedresult = 0; the if(Comparedgoods.goodsbrand__c = =Goods_brand_huawei) { - if(Goods. Goodsprice__c >Comparedgoods.goodsprice__c) { -Comparedresult = 1; -}Else if(Goods. Goodsprice__c <Comparedgoods.goodsprice__c) { +Comparedresult =-1; - } +}Else if(Comparedgoods.goodsbrand__c = =Goods_brand_lianxiang) { A if(Goods. Goodsprice__c >Comparedgoods.goodsprice__c) { atComparedresult =-1; -}Else if(Goods. Goodsprice__c = =Comparedgoods.goodsprice__c) { -Comparedresult = 0; - } - Else if(Goods. Goodsprice__c <Comparedgoods.goodsprice__c) { -Comparedresult = 1; in } - } to returnComparedresult; + } -}
Usage:
Summary: For object needs to compare the size of the time, you can implement the comparable interface, in its CompareTo method to achieve the logic of comparison. This article has the wrong place welcome to correct, has the question to welcome the message.
Salesforce 0 Basic Learning (63) comparable implementing custom sorting of Object list data