TOrderedDictionary in Delphi 12.2 (en)

With Delphi 12.2, an exciting new class has been introduced: TOrderedDictionary. This class provides a useful addition for cases where an ordered dictionary structure was previously missing.

In this post, we will take a look at how TOrderedDictionary works and how to use a custom IComparer to perform a specific sorting.

Why TOrderedDictionary?

Traditional dictionaries like TDictionary in Delphi provide fast access to key-value pairs, but they do not maintain any specific order. This is also completely analogous to standard references on data structures, where dictionaries are usually defined like sets without order.

TOrderedDictionary, however, is designed to maintain the order of elements according to their insertion order, meaning they have an order. Moreover, TOrderedDictionary allows for explicit sorting of both keys and values. You can therefore reorder the collection at will.

Basics of Using TOrderedDictionary

In the following, I have put together a simple example that illustrates how TOrderedDictionary works. In this case, we initialize a dictionary with some sample pairs, sort by different criteria, and use a custom IComparer to order the keys by English number words. The example was originally inspired by Marco’s example, where Marco left the question open as to how one could logically sort the number words he chose.

program OrderedDictionaryDemo;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  System.Generics.Defaults,
  System.Generics.Collections,
  System.Diagnostics;

const
  // String constant for the number words, can be easily extended
  NUMBER_WORDS =
    '''
     one two three four five
     six seven eight nine ten
    ''';

type
  TNumberWordComparer = class(TInterfacedObject, IComparer<string>)
  private
    FNumberWords: TArray<string>;
    function GetNumberValue(const Word: string): Integer;
  public
    constructor Create;
    // Compares two strings based on their numeric value as defined in NUMBER_WORDS
    function Compare(const Left, Right: string): Integer;
  end;

constructor TNumberWordComparer.Create;
begin
  // Split the multiline string into individual words
  FNumberWords := NUMBER_WORDS.Split([sLineBreak, ' ']);
end;

function TNumberWordComparer.GetNumberValue(const Word: string): Integer;
var
  Index: Integer;
begin
  // Find the word in the array and return the index as its value
  Index := TArray.IndexOf<string>(FNumberWords, LowerCase(Word));
  if Index >= 0 then
    Result := Index
  else
    Result := MaxInt; // Return value for words not found
end;

function TNumberWordComparer.Compare(const Left, Right: string): Integer;
begin
  // Compare the two words and return a negative value if
  // the left word-number is smaller than the right one
  Result := GetNumberValue(Left) - GetNumberValue(Right);
end;

begin
  var ODict := TOrderedDictionary<string, string>.Create;
  ODict.Add('one', 'London');
  ODict.Add('two', 'Berlin');
  ODict.Add('three', 'Rome');
  ODict.Add('four', 'Athens');
  ODict.Add('five', 'Madrid');
  ODict.Add('six', 'Bruxelles');
  ODict.Add('seven', 'Paris');

  // Sorting and displaying the elements
  Writeln('Default order:');
  for var APair in ODict do
    Writeln(APair.Key + ' - ' + APair.Value);

  // Sorting by keys and values
  ODict.SortByKeys;
  Writeln('Sorted by keys:');
  for var APair in ODict do
    Writeln(APair.Key + ' - ' + APair.Value);

  ODict.SortByValues;
  Writeln('Sorted by values:');
  for var APair in ODict do
    Writeln(APair.Key + ' - ' + APair.Value);

  // Custom sorting by number words
  ODict.SortByKeys(TNumberWordComparer.Create);
  Writeln('Sorted by number words:');
  for var APair in ODict do
    Writeln(APair.Key + ' - ' + APair.Value);
end.

Features and Flexibility

In our example, we use SortByKeys and SortByValues to sort elements by keys and values. TOrderedDictionary thus offers us a convenient way to change the sorting order as needed.

Of particular interest is the ability to implement a custom IComparer. In this case, we sort by English number words (onetwothree, etc.) using TNumberWordComparer.

The GetNumberValue method searches an array of number words to find the index of a word. This index is used as the numeric value for sorting. If a word is not found, the function returns MaxInt, placing it at the end of the list. The array can be extended as needed. The use of a multi-line string introduced in Delphi 12 makes initializing the array via the Split function easy to maintain.

Important: The comparer is only used when explicitly sorting, not implicitly when new pairs are inserted. Therefore, the dictionary remains a static data structure.

Conclusion

The new TOrderedDictionary class is an interesting addition to the System.Generics.Collections unit in Delphi 12.2. With its ability to maintain the order of insertions and perform flexible sorting, it offers developers a versatile and practical solution for managing key-value pairs.

TOrderedDictionary in Delphi 12.2

Mit Delphi 12.2 wurde eine spannende neue Klasse eingeführt: TOrderedDictionary. Diese Klasse bringt eine sinnvolle Erweiterung, für Fälle wo man bisher eine geordnete Dictionary-Struktur vermisst hat.

 In diesem Beitrag schauen wir uns an, wie TOrderedDictionary funktioniert und wie man mithilfe eines benutzerdefinierten IComparer eine spezielle Sortierung vornimmt.

Warum TOrderedDictionary?

Traditionelle Dictionaries wie TDictionary in Delphi bieten schnellen Zugriff auf Schlüssel-Wert-Paare, aber sie behalten keine bestimmte Reihenfolge bei. Dies ist auch völlig analog zu Standardwerken über Datenstrukturen, wo Dictionaries üblicherweise wie Mengen ohne Ordnung definiert werden.  

TOrderedDictionary hingegen ist darauf ausgelegt, die Reihenfolge der Elemente nach ihrer Einfügereihenfolge beizubehalten, sie haben also eine Ordnung. Darüber hinaus erlaubt TOrderedDictionary eine explizite Sortierung sowohl der Schlüssel als auch der Werte. Man kann also die Ordnung beliebig umsortieren.

Grundlagen der TOrderedDictionary-Verwendung

Im Folgenden habe ich ein einfaches Beispiel zusammengestellt, das die Funktionsweise von TOrderedDictionaryillustriert. In diesem Fall initialisieren wir ein Dictionary mit einigen Beispielpaaren, sortieren nach verschiedenen Kriterien und verwenden einen benutzerdefinierten IComparer, um die Schlüssel nach englischen Zahlenwörtern zu ordnen. Das Beispiel ist ursprünglich von Marcos Beispiel inspiriert, in dem Marco aber die Frage offen lässt, wie man dann tatsächlich die von ihm gewählten Zahlenworte logisch sortieren kann. 

program OrderedDictionaryDemo;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  System.Generics.Defaults,
  System.Generics.Collections,
  System.Diagnostics;

const
  // Stringkonstante für die Zahlenwörter, kann einfach beliebig erweitert werden 
  NUMBER_WORDS =
    '''
     one two three four five
     six seven eight nine ten
    ''';

type
  TNumberWordComparer = class(TInterfacedObject, IComparer<string>)
  private
    FNumberWords: TArray<string>;
    function GetNumberValue(const Word: string): Integer;
  public
    constructor Create;
    // Vergleicht zwei Zeichenfolgen basierend auf ihrem numerischen Wert, wie in NUMBER_WORDS definiert
    function Compare(const Left, Right: string): Integer;
  end;

constructor TNumberWordComparer.Create;
begin
  // Zerlege den Multiline-String in einzelne Wörter
  FNumberWords := NUMBER_WORDS.Split([sLineBreak, ' ']);
end;

function TNumberWordComparer.GetNumberValue(const Word: string): Integer;
var
  Index: Integer;
begin
  // Suche das Wort im Array und gebe den Index als Wert zurück
  Index := TArray.IndexOf<string>(FNumberWords, LowerCase(Word));
  if Index >= 0 then
    Result := Index
  else
    Result := MaxInt; // Rückgabewert für nicht gefundene Wörter
end;

function TNumberWordComparer.Compare(const Left, Right: string): Integer;
begin
  Vergleiche die beiden Worte und gebe einen negativen Wert zurück, wenn
  die linke Wort-Zahl kleiner als die rechte ist.
  Result := GetNumberValue(Left) - GetNumberValue(Right);
end;

begin
  var ODict := TOrderedDictionary<string, string>.Create;
  ODict.Add('one', 'London');
  ODict.Add('two', 'Berlin');
  ODict.Add('three', 'Rome');
  ODict.Add('four', 'Athens');
  ODict.Add('five', 'Madrid');
  ODict.Add('six', 'Bruxelles');
  ODict.Add('seven', 'Paris');

  // Sortieren und Ausgabe der Elemente
  Writeln('Standardreihenfolge:');
  for var APair in ODict do
    Writeln(APair.Key + ' - ' + APair.Value);

  // Sortierung nach Schlüsseln und Werten
  ODict.SortByKeys;
  Writeln('Nach Schlüsseln sortiert:');
  for var APair in ODict do
    Writeln(APair.Key + ' - ' + APair.Value);

  ODict.SortByValues;
  Writeln('Nach Werten sortiert:');
  for var APair in ODict do
    Writeln(APair.Key + ' - ' + APair.Value);

  // Benutzerdefinierte Sortierung nach Zahl-Worten
  // Wichtig: In-Place-Create vermeiden. Stattdessen Variable verwenden 
    var GNumberComparer: IComparer<string> := TNumberWordComparer.Create;
    ODict.SortByKeys(GNumberComparer);
  Writeln('Sortiert nach Zahl-Worten:');
  for var APair in ODict do
    Writeln(APair.Key + ' - ' + APair.Value);
end.

Besonderheiten und Flexibilität

In unserem Beispiel nutzen wir SortByKeys und SortByValues, um Elemente nach Schlüsseln und Werten zu sortieren. TOrderedDictionary bietet uns somit eine bequeme Möglichkeit, die Sortierreihenfolge nach Bedarf zu ändern. 

Besonders interessant ist die Möglichkeit, einen benutzerdefinierten IComparer zu implementieren. In diesem Fall sortieren wir nach englischen Zahlenwörtern (onetwothree usw.) mithilfe von TNumberWordComparer.

Dessen Methode GetNumberValue durchsucht ein Array mit Zahlenwörtern, um den Index eines Worts zu finden. Dieser Index wird als numerischer Wert für die Sortierung verwendet. Falls ein Wort nicht gefunden wird, gibt die Funktion MaxInt zurück, wodurch es am Ende der Liste landet. Das Array lässt sich beliebig erweitern. Die Verwendung eines in Delphi 12 eingeführten Multi-Line-Strings macht das Intialisieren des Arrays über die Split-Funktion leicht wartbar.

Wichtig: Der Comparer wird nur beim konkreten Sortieren verwendet und nicht etwa implizit, wenn neue Paare eingefügt werden. Das Dictionary bleibt also weiterhin eine statische Datenstruktur. 

Fazit

Die neue TOrderedDictionary-Klasse ist eine interessante Erweiterung der System.Generics.Collections-Unit in Delphi 12.2. Mit ihrer Fähigkeit, die Reihenfolge von Einfügungen beizubehalten und eine flexible Sortierung durchzuführen, bietet sie Entwicklern eine vielseitige und praktische Lösung für die Verwaltung von Schlüssel-Wert-Paaren.

TTask / TThreadPool may keep interfaced objects alive

UPDATE: The issue described here has been marked „resolved“ on May, 5th 2017, so we should see corrected behaviour in one of the next deliveries.

I am using TTask.Run quite a lot in projects and in many of my demos. I won’t go into the details of how to use TTask here, but I only want to highlight that there is still an open issue, which may cause interfaced objects to be destroyed much later, than you would expect. Ultimately this may lead to a much higher memory footprint of your application.

As of Delphi 10.1 Update 2 the issue is still marked open on quality.emabaracdero.com – you might vote for it, if your code is affected by it.

Interfaced objects use automatic reference counting for lifecycle management:

var
  LFoo : IFoo
begin
  LFoo := TFoo.Create;
  //work with LFoo
end;  //LFoo goes out of scope, its reference counter will go to zero,
      // thus it will be destroyed here automatically.

With TTask.Run you can start background threads, that will execute code passed in as anonymous method:

var
  LFoo : IFoo
begin
  LFoo := TFoo.Create;
  TTask.Run(procedure
    begin
      Foobar(LFoo); //Work with LFoo 
    end;
  ).Waitfor; //Wait for task/thread to be completed 
end;  //LFoo goes out of scope, its reference counter SHOULD go to zero,
      // thus it SHOULD be destroyed here automatically.   

Unfortunately the above does not work as expected. The internals of TTask (actually TThreadpool) keep a reference to the (already finished) task and prevent the instance of TFoo, which is referenced by LFoo, to be destroyed automatically. At least when the TThreadPool gets destroyed, all those kept references will be released and the instances will be destroyed, thus they won’t report as memory leak (with ReportMemoryLeaksOnShutDown).

In other words: you will have to set LFoo to nil manually – until this issue gets solved in one of the next updates.

  TTask.Run(procedure
    begin
      Foobar(LFoo); //Work with LFoo 
    end;
  ).Waitfor; //Wait for task/thread to be completed 
  LFoo := nil; //Depending on your logic, this could also be done inside TTask.Run
end;    
Wir benutzen Cookies um die Nutzerfreundlichkeit der Webseite zu verbessen. Durch Deinen Besuch stimmst Du dem zu.