Alan Clark
Alan Clark

Reputation: 2079

How to add to a generic TList<Value, TDictionary> in Delphi

I'm trying to use a generic dictionary of objects where they key is a string, and the value is a TDictionary. Is this possible? I don't see why not, but I don't know what the syntax would be to add to the dictionary. I've tried a few things but can't quite get it right. Perhaps TPair has to be used somehow.

This code demonstrates what I'm trying to do (it doesn't compile, not enough parameters in AddOrSetValue).

program DictTest;

{$APPTYPE CONSOLE}

uses
  SysUtils, Generics.Collections;

type
  TLookup = TDictionary<integer, integer>;
  TCache = TDictionary<string, TLookup>;

var
  Cache : TCache;

begin
  Cache := TCache.Create;
  try
    Cache.AddOrSetValue['Hi', ([1, 2])];
  finally
    Cache.Free;
  end;
end.

Upvotes: 1

Views: 3823

Answers (2)

user394386
user394386

Reputation: 21

Try this:

program DictTest; 

{$APPTYPE CONSOLE} 

uses 
  SysUtils, Generics.Collections; 

type 
  TLookup = TDictionary<integer, integer>; 
  TCache = TDictionary<string, TLookup>; 

var 
  Cache : TCache; 
  ALookup: TLookup;
begin 
  Cache := TCache.Create; 
  try 
    ALookup := TLookup.Create;
    ALookup.Add(1, 2);
    Cache.AddOrSetValue['Hi', ALookup]; 
  finally 
    Cache.Free; 
  end; 
end. 

Upvotes: 1

Mason Wheeler
Mason Wheeler

Reputation: 84550

If your Value is a dictionary then Cache.Add's second parameter has to be a dictionary. So:

Cache.AddOrSetValue('Hi', TLookup.Create);
Cache['Hi'].AddOrSetValue(1, 2);

But be careful using AddOrSetValue when the value is an object. If you're not careful you can end up with memory leaks.

Upvotes: 2

Related Questions