* * *

Author Topic: [SOLVED] Generics.Collections TDictionary indexed access  (Read 1253 times)

Eugene Loza

  • Hero Member
  • *****
  • Posts: 561
    • My "almost daily" development blog
[SOLVED] Generics.Collections TDictionary indexed access
« on: January 30, 2018, 12:41:54 am »
Hi all!
I'm using Generics.Collections from FPC3.1.1 (trunk) and I need to access a random item in a TObjectDictionary. What is the correct syntax to? EQ := AllData.Items[index] (like in TObjectList) raises error "Dictionary key does not exist".
And another question:
Are items in TObjectDictionary stored sorted by the key? E.g. that the i+1 value would have key > than that of i-th element. (Key is TDateTime).

Actually, using a sorted TObjectList in the code should work for me too, but TObjectDictionary is practically a bit better in my case.
« Last Edit: January 31, 2018, 03:27:33 pm by Eugene Loza »
Lazarus 1.9 + FPC 3.1.1 Debian Jessie 64 bit.

My Free and Open Source games in Lazarus/FreePascal/CastleGameEngine:
https://decoherence.itch.io/
(and some ancient games in Turbo Pascal too)
Sources are here: https://github.com/eugeneloza?tab=repositories

Thaddy

  • Hero Member
  • *****
  • Posts: 6529
Re: Generics.Collections TDictionary indexed access
« Reply #1 on: January 30, 2018, 08:12:44 am »
A dictionary index is of type TKey, not of type integer.
You can use TObjectList<T> if you need access by ordinal index.
Ada's daddy wrote this:"Fools are my theme, let satire be my song."

marcov

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 6403
Re: Generics.Collections TDictionary indexed access
« Reply #2 on: January 30, 2018, 10:32:32 am »
Dictionaries are not sorted, but you can iterate them, just do

for x in dict.values do
  ...

For ordered collections I use my own lightmap, which I later made somewhat compatible to tdictionary (basic methods and properties have the same name).

Though as principle it is more a generic tstringlist like map.

http://www.stack.nl/~marcov/lightcontainers.zip

Note that the demoes haven't been updated to use the Tdictionary like methods (like addobject and trygetvalue and .values etc), but use the older equivalent putpair and locate.


Eugene Loza

  • Hero Member
  • *****
  • Posts: 561
    • My "almost daily" development blog
Re: Generics.Collections TDictionary indexed access
« Reply #3 on: January 31, 2018, 03:27:21 pm »
Thanks a lot, Thaddy, marcov!
I'll stick with a sorted TObjectList then.
Lazarus 1.9 + FPC 3.1.1 Debian Jessie 64 bit.

My Free and Open Source games in Lazarus/FreePascal/CastleGameEngine:
https://decoherence.itch.io/
(and some ancient games in Turbo Pascal too)
Sources are here: https://github.com/eugeneloza?tab=repositories

 

Recent

Get Lazarus at SourceForge.net. Fast, secure and Free Open Source software downloads Open Hub project report for Lazarus