Last active
August 29, 2015 14:19
-
-
Save hasanthaera/6fbb48bc9933b0561263 to your computer and use it in GitHub Desktop.
Salesforce - compare values through list of objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment