Quantcast
Channel: Delphi – The Wiert Corner – irregular stream of stuff
Viewing all articles
Browse latest Browse all 1440

Delphi: updating a (potentially non-existing) item in a generic TDictionary: use ExtractPair. Except in Delphi 2010/XE.

$
0
0

“Documented” in Delphi 2010, [Archive.is] Generics.Collections.TDictionary.ExtractPair – RAD Studio VCL Reference, and functioning bug-free since Delphi XE2, but still hardly documented, [Archive.is] System.Generics.Collections.TDictionary.ExtractPair – XE2 API Documentation is the easiest way to get a value out of a dictionary and updating it, even if it does not exist.

ExtractPair extracts the TPair<TKey, TValue> if it exists (and removes it from the dictionary) or returns a Default initialised one if not. Though Default is still not documented, you can find an example at [WayBack] How to properly free records that contain various types in Delphi at once? – Stack Overflow.

Example code for ExtractPair:

  FEceptionDictionary := TDictionary<TExceptionKey, Integer>.Create();

...

var
  ExceptionCountPair: TPair<TExceptionKey,Integer>;
begin
  TMonitor.Enter(FEceptionDictionary);
  try
    ExceptionCountPair := FEceptionDictionary.ExtractPair(ExceptObj.ClassType); // extracts and removed from dictionary!
    FEceptionDictionary.Add(ExceptionCountPair.Key, ExceptionCountPair.Value + 1); // use Value as count
  finally
    TMonitor.Exit(FEceptionDictionary);
  end;
end;

In Delphi 2010 and XE it was buggy (see [WayBack] QualityCentral 80947: TDictionary.ExtractPair Fails and creates memory leak via [WayBack] generics – Delphi TPair Exception – Stack Overflow), but since then it works fine, and now is properly documented:

[WayBack] System.Generics.Collections.TDictionary.ExtractPair – RAD Studio API Documentation

Returns the TPair<TKey,TValue> pair with the specified Key and [WayBackremoves the returned pair from a dictionary.

If the dictionary does not contain the specified Key, the returned pair contains a default TValue.

–jeroen


Viewing all articles
Browse latest Browse all 1440

Trending Articles