[英]Sorting TDictionary by a key of Integer in ascending order
如何在 Delphi 2009 中按升序按 Integer 键对 TDictionary 进行排序?
The RTL TDictionaries are not sorted and cannot be sorted (other than by hash, which they are). RTL TDictionaries 未排序且无法排序(它们是按哈希排序的除外)。 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.