Frage

Out from a complex scoring process I have a TDictionary structure:

target_results : TDictionary<longint, double>;

The key represents an id from a record in a MySQL table. From that id I can retrieve a filedate and a filename. I need to deliver these results ordered by one of these options:

1. dictionary value (solved: I'm doing this by assigning the dictionary to an array, sorting it and then retrieving the filename and date for each result, from the database)
2. filename
3. filedate

I'm thinking about using a TVirtualTable (from Devart) since I'm already using UniDAC in this project. Can someone advise a faster, sort flexible, more native approach into this?

War es hilfreich?

Lösung

You cannot sort a dictionary. The only comparable structure with sorting build in is Judy array. However you can sort items that dictionary points to. You already seem to have sorted the keys if I understand you correctly. Now you do the same for other data if you want to sort by something different. The algorithm would be:

  1. Define a class or a record containing all data that is relevant for you
  2. Iterate or enumerate the TDictionary items into a generic TList and for each item fill the class or record with the data from the database
  3. Sort the items in the TList by the appropriate criteria. You can see an example of such sorting here: http://delphi.about.com/od/delphitips2009/qt/sort-generic.htm

Bear in mind that this will be O(N) for iterating where N is not only number of items in the database but number of buckets in the hash table. Then there is additional overhead of geting the data from the database for each item and finally there is O(NLogN) for quick sort.

TDictionary as all hash tables is meant for lookup, it is good at that and bad at other tasks like iteration or even sorting. If you want to speed that up use a separate list sorted by appropriate key so you can then just iterate already sorted list and get data from the DB. If sorting is really important and done a lot of times then use binary trees instead of hash tables. You can have one binary tree for each search field. With binary trees I mean balanced binary trees like AVL tree.

For instance binary trees are good for that because they stay sorted on insertions. Can't help you more without further data available.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top