Sorting TDictionary by a key of Integer in ascendi

2020-07-06 04:52发布

How can I sort TDictionary by a key of Integer in ascending order in Delphi 2009?

1条回答
叼着烟拽天下
2楼-- · 2020-07-06 05:30

The RTL TDictionaries are not sorted and cannot be sorted (other than by hash, which they are). You need to use another container if you wish to sort either the keys or the values. For example :

program Project1;

{$APPTYPE CONSOLE}

uses
  Generics.Collections, Generics.Defaults, SysUtils;

var
  LDict : TDictionary<integer, string>;
  i, j : integer;
  LArray : TArray<integer>;
begin
  LDict := TDictionary<integer, string>.Create;
  try
    // Generate some values
    Randomize;
    for i := 0 to 20 do begin
      j := Random(1000);
      LDict.AddOrSetValue(j, Format('The Value : %d', [j]));
    end;
    WriteLn('Disorder...');
    for i in LDict.Keys do
      WriteLn(LDict.Items[i]);
    // Sort
    LArray := LDict.Keys.ToArray;
    TArray.Sort<integer>(LArray);
    WriteLn('Order...');
    for i in LArray do
      WriteLn(LDict.Items[i]);
  finally
    LDict.Free;
  end;
  Readln;
end.
查看更多
登录 后发表回答