Reputation: 41
I create a TStringList
that contains name/value pair and I want to sort TStringList
according to it's values and then Names with max value are assigned to Labels.
SL: TStringList;
SL:= TStringList.Create;
SL.Values['chelsea']:= '5';
SL.Values['Liverpool']:= '15';
SL.Values['Mancity']:= '10';
SL.Values['Tot']:= '0';
SL.Values['Manunited']:= '20';
Finally this TStringList
must be sorted in According to values. actually first name must be a name with highest value.
Upvotes: 3
Views: 572
Reputation: 613491
You can do this using the CustomSort
method. Like this:
{$APPTYPE CONSOLE}
uses
SysUtils, Classes;
function StringListSortProc(List: TStringList; Index1, Index2: Integer): Integer;
var
i1, i2: Integer;
begin
i1 := StrToInt(List.ValueFromIndex[Index1]);
i2 := StrToInt(List.ValueFromIndex[Index2]);
Result := i2 - i1;
end;
var
SL: TStringList;
Index: Integer;
begin
SL := TStringList.Create;
try
SL.Values['Chelsea'] := '5';
SL.Values['Liverpool'] := '15';
SL.Values['Man City'] := '10';
SL.Values['Spurs'] := '0';
SL.Values['Man United'] := '20';
WriteLn('Before sort');
for Index := 0 to SL.Count-1 do
WriteLn(' ' + SL[Index]);
SL.CustomSort(StringListSortProc);
WriteLn;
WriteLn('After sort');
for Index := 0 to SL.Count-1 do
WriteLn(' ' + SL[Index]);
finally
SL.Free;
end;
ReadLn;
end.
I can't remember when the ValueFromIndex
method was added. If it is not present in Delphi 7 then you can emulate it like this:
function ValueFromIndex(List: TStringList; Index: Integer): string;
var
Item: string;
begin
Item := List[Index];
Result := Copy(Item, Pos('=', Item) + 1, MaxInt);
end;
function StringListSortProc(List: TStringList; Index1, Index2: Integer): Integer;
var
i1, i2: Integer;
begin
i1 := StrToInt(ValueFromIndex(List, Index1));
i2 := StrToInt(ValueFromIndex(List, Index2));
Result := i2 - i1;
end;
Program output:
Before sort Chelsea=5 Liverpool=15 Man City=10 Spurs=0 Man United=20 After sort Man United=20 Liverpool=15 Man City=10 Chelsea=5 Spurs=0
Upvotes: 4