Sort a list of sObjects: quick and dirty -or- elegant

2 Oct

Quick and Dirty

Here is a method that I’ve implemented to sort lists of objects by combinations of fields. I don’t claim that it is pretty, but it has worked for me.

public static list SortTrf (list iMyObjList) {
  list SortStringList = new list();
  list SortedObjList  = new list();
  map ObjMap = new map();
  MyObj__c TmpMyObj;
  String UniqueValue;
	
  for (MyObj__c m : iMyObjList) {
    UniqueValue = PadZeros(Integer.valueOf(m.SequencingField__c), 5) + m.Name;
    SortStringList.add(UniqueValue);
    ObjMap.put(UniqueValue, m);
  }
  SortStringList.sort();
  for (String s : SortStringList) {
    TmpMyObj = ObjMap.get(s);
    if (TmpMyObj != null) SortedObjList.add(TmpMyObj);
  }
  return SortedObjList;
}

With the help of a method from my other post.

public static String PadZeros(Integer Num, Integer Len) {
  String s = String.valueOf(Num);
  while (s.length() < Len) s = '0' + s;
  return s;
}

Elegant

Implement the Comparable interface on a sub-class allows a list of the objects to be sorted using a familiar '.sort()' method.

public class MyObjWrap implements Comparable {
  public MyObj__c      MyObj       {get; set;}
    
  /* compareTo - sort using a field on MyObj__c */
  public Integer compareTo(Object compareTo) {
     ObjWrap TheObjWrap= (ObjWrap) compareTo;
     if (MyObj.MyField__c == TheObjWrap.MyObj.MyField__c) return 0;
     if (MyObj.MyField__c > TheObjWrap.MyObj.MyField__c) return 1;
     return -1;        
  }
}

Now that your subclass is setup, you can use the built-in sort method for the instantiated object list.

list MyObjList = new list();
// load the list with your object
MyObjList.sort();