How can I sort TDictionary by a key of Integer in ascending order in Delphi 2009?
First, sort the keys alphabetically using key_value. iterkeys() function. Second, sort the keys alphabetically using the sorted (key_value) function & print the value corresponding to it. Third, sort the values alphabetically using key_value.
Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.
Use dict. items() to get a list of tuple pairs from d and sort it using a lambda function and sorted(). Use dict() to convert the sorted list back to a dictionary. Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the second argument.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With