Miguel E
Miguel E

Reputation: 1336

Iterate generic collection top down (TDictionary)

I have a TDictionary. It's being filled with an extensive loop. When the loop finishes I need to retrieve the 10 keys(string) with more score(integer). What would be the most efficient way to accomplish this?

In Objective-C(Cocoa) I do it with:

NSArray *top_words_sorted_array = [top_words_dictionary keysSortedByValueUsingSelector:@selector(compare:)];

and then iterating the new sorted array. How can I do it in Delphi?

Upvotes: 3

Views: 716

Answers (2)

David Heffernan
David Heffernan

Reputation: 613262

The equivalent Delphi code to your Cocoa code is:

type
  TScorePair = TPair<string,Integer>;
var
  ScoresArray: TArray<TScorePair>;
....
ScoresArray := Scores.ToArray;
TArray.Sort(ScoresArray,
  TComparer<TScorePair>.Construct( 
    function(const L, R: TScorePair): Integer
    begin
      Result := R.Value - L.Value;
    end
  )
);

If your dictionary is very large then this will not be the most efficient solution. On the other hand, it's probably the quickest and easiest approach to implement.

Upvotes: 5

Leonardo Herrera
Leonardo Herrera

Reputation: 8406

Do you need to access it as a map (dictionary), or a plain array suffices?

If you must have it as a map, I would take a look at DeHL.Collections, perhaps DeHL.Collections.DoubleSortedBidiMap does what you need. The project page says it is discontinued but I use it everyday and never have a problem.

Upvotes: 0

Related Questions