salesforce 零基础学习(六十三)Comparable实现Object列表数据的自定义排序

项目中通常有些需求为需要将某个sObject的数据列表按照某种规则排序显示到前台页面上,但是list上面的sort远远满足不了复杂的功能,此种情况需要自定义比较两个object大小的方法,所以需要创建Compare相关的类实现Comparable接口。

需求:实现Goods__c列表排序,GoodsBrand__c为华为的按照价格升序排序,GoodsBrand__c为联想的按照价格降序排列。

 public without sharing class ComparedGoods implements Comparable{
private Goods__c goods{get;set;} private static final String GOODS_BRAND_HUAWEI = '华为'; private static final String GOODS_BRAND_LIANXIANG = '联想'; public ComparedGoods(Goods__c obj) {
goods = obj;
} public Integer compareTo(Object objectToCompareTo) {
Goods__c comparedGoods = (Goods__c)objectToCompareTo;
Integer comparedResult = 0;
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) {
if(goods.GoodsPrice__c > comparedGoods.GoodsPrice__c) {
comparedResult = -1;
} else if(goods.GoodsPrice__c == comparedGoods.GoodsPrice__c) {
comparedResult = 0;
}
else if(goods.GoodsPrice__c < comparedGoods.GoodsPrice__c) {
comparedResult = 1;
}
}
return comparedResult;
}
}

用法:

salesforce 零基础学习(六十三)Comparable实现Object列表数据的自定义排序

总结:针对object需要比较大小的时候,可以实现Comparable接口,在其compareTo方法中实现比较的逻辑即可。此篇有错误的地方欢迎指正,有问题欢迎留言。

上一篇:jquery 跨域请求


下一篇:word20161214