在 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.
关于delphi - 按 Integer 键按升序对 TDictionary 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31256891/