按整数的键按升序对 TDictionary 进行排序

Sorting TDictionary by a key of Integer in ascending order

如何在 Delphi 2009 中按 Integer 的键对 TDictionary 进行升序排序?

RTL TDictionaries 未排序且无法排序(除了按哈希排序,它们是排序的)。如果您希望对键或值进行排序,则需要使用另一个容器。例如:

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.