Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Sort a Generic List using Anonymous Comparer Delphi Method

Title: Sort a Generic List using Anonymous Comparer Delphi Method Delphi 2009 adds Generics and Anonymous methods to the Delphi language. When you have objects in some list - one of a commonly required tasks is to sort the list: either ascending, descending or using some list-specific algorithm. Using anonymous methods you can apply the sorting function directly "inline" with the call to the Sort method. TList.Sort(IComparer) Suppose you have a list of integer numbers. Your task is to sort the numbers in the list. Here's the code: uses generics.defaults, generics.collections,... ... type TIntegerComparer = TComparer; ... var lg : TList; n : integer; begin lg := TList.Create; try lg.Add(2) ; lg.Add(4) ; lg.Add(3) ; lg.Add(4) ; lg.Add(5) ; lg.Add(1) ; //will display 2,4,3,4,5,1 for n in lg do ShowMessage(IntToStr(i)) ; //default ascending comparer lg.Sort(TComparer.Default) ; //will display 1,2,3,4,4,5 for n in lg do ShowMessage(IntToStr(i)) ; //descending using an anonymous method lg.Sort(TIntegerComparer.Construct( function (const L, R: integer): integer begin result := R - L; end )) ; //will display 5,4,4,3,2,1 for n in lg do ShowMessage(IntToStr(i)) ; finally lg.Free; end; end; Note: the TList.Sort methods expects an IComparer object. IComparer is an interface defined in the generics.defaults unit. TComparer, also defined in the Generics.Defaults, is an abstract base class for IComparer implementations. The Construct method of the TComparer is a class method defined as: class function Construct(const Comparison: TComparison): IComparer; The above returns an IComparer we need for the Sort method AND accepts an anonymous method: TComparison = reference to function(const Left, Right: T): Integer; Finally, you have a Sort method with an anonymous method as "parameter": lg.Sort(TIntegerComparer.Construct( function (const L, R: integer): integer begin result := R - L; end )) ; For a non-generic TList object: How to sort items in a TList object.