There are times that we cannot use the comparator class for comparisons such as sorting a list of custom objects with ordering according to a given field,
Following code snippet resolve the issue,
List<Sobject> sObjectList = <---provide list of Objects eg: Schools--->
String orderBy = <---provide orderBy field Name eg: School Name--->
String order = <--ASC or DESC--->
List<Sobject> resultList = new List<Sobject>();
Map<object, List<Sobject>> sortMap = new Map<object, List<Sobject>>();
if(sObjectList.isEmpty() || orderBy || order) return;
for(Sobject ob : sObjectList){
if(sortMap.get(ob.get(orderBy)) == null)
sortMap.put(ob.get(orderBy), new List<Sobject>());
sortMap.get(ob.get(orderBy)).add(ob);
}
//Sort the keys
List<object> keys = new List<object>(sortMap.keySet());
keys.sort();
for(object key : keys){
resultList.addAll(sortMap.get(key));
}
//create sorted list
sObjectList.clear();
if(order.toLowerCase() == 'ASC'){
for(Sobject ob : resultList){
sObjectList.add(ob);
}
}else if(order.toLowerCase() == 'DESC'){
for(integer i = resultList.size()-1; i >= 0; i--){
sObjectList.add(resultList[i]);
}
}

No comments:
Post a Comment