TDictionary weird behavior in delphi

I have the following problem:

I fill in the dictionary with some values ​​and would like to return them in the exact exact order in which I filled them.

Somehow this does not work when I repeat the elements, they are sorted in an illogical order (IMDO).

After starting the following program:

program Project1; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils, System.Generics.Collections; var Dictionary: TDictionary<LongWord, string>; aPair: TPair<LongWord, string>; begin Dictionary := TDictionary<LongWord, string>.Create; Dictionary.add(1, 'First Item'); Dictionary.add(2, 'Second Item'); Dictionary.add(3, 'Third Item'); Dictionary.add(4, 'Forth Item'); Dictionary.add(5, 'Fifth Item'); Dictionary.add($FFFFFFFF, 'Longword Item'); for aPair in Dictionary do writeln(aPair.Value); readln; end. 

I got the following results:

 Forth Item Longword Item First Item Third Item Second Item Fifth Item 

Am I doing something wrong?

Tested on XE5 and Rad Studio Berlin, same results.

Thanks for the help.

+5
source share
1 answer

The Delphi dictionary class is unordered. It behaves as designed. If you want to keep an order, you need to use an ordered data structure. For example, an array or a list.

If you want to have ordered access as well as O (1) search, you will need to support two collections in tandem. One array or list for ordered access and in the tandem dictionary for O (1) search. Or, alternatively, find a library that offers an ordered implementation of a dictionary.

+6
source

Source: https://habr.com/ru/post/1262143/


All Articles