Sorting TDictionary by a key of Integer in ascending order

我与影子孤独终老i 提交于 2020-06-10 11:15:47

问题


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


回答1:


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.


来源:https://stackoverflow.com/questions/31256891/sorting-tdictionary-by-a-key-of-integer-in-ascending-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!