An easy way to create an inverted TDictionary <TKey, TValue> key list?
Is there an easy way to take a key list TDictionary<TKey,TValue>
and reverse its order?
I could use the classic one for the I: = ... loop, but as I see it is there TList<T>.Reverse
in Generics.Collections, maybe there is better / shorter one.
Update: a for loop I: = downto will have the same useless order, so the best way is to use a separate TList<TKey>
source to share
Keys in TDictionary are unordered. The class makes no guarantees over its order, and the actual order that is used is not the order in which they were added. Reversing the order of an unordered dictionary is a meaningless operation.
Delphi does not ship with an ordered dictionary class, although there are third party classes. If your usage is relatively straightforward, you can manage an additional list containing the keys in the order you want.
source to share
In my case, I am using TDictionary <Tkey, TValue>. TKeyCollection .
function compareKeyReverse(const L, R: TKey): Integer;
begin
// Reverse compare keys
// if TKey = String, uncomment code below
// Result := - SysUtils.CompareText(L, R);
end;
function getReverseSortedKeyArray(dictionary: TDictionary<TKey, TValue>): TArray<TKey>;
var
keyArray: TArray<TKey>;
keyCollecttion: TDictionary<Tkey, TValue>.TKeyCollection;
begin
keyCollecttion:= TDictionary<Tkey, TValue>.TKeyCollection.Create(dictionary);
try
keyArray:= valueCollecttion.ToArray;
TArray.Sort<Tkey>(keyArray, TComparer<Tkey>.Construct(compareKeyReverse));
finally
keyCollecttion.Free;
end;
Result := keyArray;
end;
Usage example:
var
key: TKey;
keyArray : TArray<TKey>;
begin
keyArray := getReverseSortedKeyArray (dictionary);
for key in keyArray do
begin
// ...
end;
end;
source to share