Jump to content
Sign in to follow this  
jarto

Sorting arrays and lists

Recommended Posts

This is a tutorial for sorting arrays and lists in Smart Mobile Studio.

String arrays and TStringList are pretty easy to sort. You only need to call Sort:

  var strarr: array of String;
  ...
  strarr.Sort;

  var strlist: TStringList;
  strlist:=TStringList.Create;
  ...
  strlist.Sort;

But how do you sort arrays of records or arrays of classes? For example:

  TSortData = record
    Id: Integer;
    Data: String;
  end;

You can't simply call Sort as your application does not know how you want to sort the records. You solve this by using a comparison function:

function CompareSortData(Item1, Item2: TSortData): Integer;
begin
  result:=CompareStr(Item1.Data, Item2.Data);
end;

.
.
.

var objarr: array of TSortData;
...
objarr.Sort(@CompareSortData);

The comparison function should return a negative number if Item1 is smaller, positive number if Item1 is bigger and 0 if they are equal.

In Smart Mobile Studio you can also use anonymous methods:

var objarr: array of TSortData;
...
objarr.Sort( function(Item1, Item2: TSortData): Integer
  begin 
    result:=CompareStr(Item1.Data,Item2.Data);
  end);

Comparison functions can also be used for TList and even for TStringList. For example, you may want to have greater control over how names are sorted (eliminating prefixes like von):

function EliminatePrefix(Name: String): String;
const Prefixes: array[0..1] of String = ['von ','af '];
begin
  result:=Name;
  for var a:=0 to High(Prefixes) do begin
    if pos(Prefixes[a],result)=1 then begin
      Delete(result,1,Length(Prefixes[a]));
      exit;
    end;
  end;
end;

.
.
.

var StrList:=TStringList.Create;
StrList.Add('Perry');
StrList.Add('Miller');
StrList.Add('von Essen');
StrList.Add('Stockton');
StrList.Add('af Trolle');

StrList.Sort( function(Name1,Name2: String): Integer
  begin
    result:=CompareStr(EliminatePrefix(Name1),EliminatePrefix(Name2));
  end);

for var a:=0 to StrList.Count-1 do WriteLn(StrList[a]);

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×