Jump to content

Sorting arrays and lists


Recommended Posts

  • Administrators

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]);

 

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...