Associative array in Delphi , array with string key is possible?
You can use TDictionary<string,string>
from the Generics.Collections
unit.
var
Dict: TDictionary<string,string>;
myValue: string;
....
Dict := TDictionary<string,string>.Create;
try
Dict.Add('hostname', 'localhost');
Dict.Add('database', 'test');
//etc.
myValue := Dict['hostname'];
finally
Dict.Free;
end;
And so on and so on.
If you want a dictionary that contains a dictionary, you can do use TDictionary<string, TDictionary<string,string>>
.
However, when you do that you'll need to take special care over the lifetime of the dictionary items that are contained in the outer dictionary. You can use TObjectDictionary<K,V>
to help manage that for you. You'd create one of these objects like this:
TObjectDictionary<string, TDictionary<string,string>>.Create([doOwnsValues]);
This TObjectDictionary<k,V>
operates the same was as a traditional TObjectList
with OwnsObjects
set to True
.
You can use tStrings and tStringList for this purpose, but 2d arrays are out of the scope of these components.
Usage;
var
names : TStrings;
begin
...
names := TStringList.Create;
...
...
names.values['ABC'] := 'VALUE of ABC' ;
...
...
end ;