简体   繁体   中英

How to sort a TStringList according to it's values in Delphi 7

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM