Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest way to work with associative strings (key/values)?

Tags:

delphi

I have a lot of constants that are somehow related, at some point I need to pair them, something like this:

const
  key1 = '1';
  key2 = '2';
  key3 = '3';

  value1 = 'a';
  value2 = 'b';
  value3 = 'c';

I want to avoid doing:

if MyValue = key1 then Result := value1;

I know how to do it with string lists using:

MyStringList.Add(key1 + '=' + value1);
Result := MyStringList.Values[key1];

But, is there any simpler way to do this?

like image 616
Fabio Gomes Avatar asked Oct 29 '08 18:10

Fabio Gomes


2 Answers

Yes, assignment can be done this way instead, avoiding manual string concatenation:

MyStringList.Values[Key1] := Value1;
like image 81
Jozz Avatar answered Sep 29 '22 23:09

Jozz


Do a wrapper around your "value"

TMyValue = class
  value: String;
end;

Then use this:

myValue := TMyValue.Create;
myValue.Value = Value1;

MyStringList.AddObject(Key1, Value1);

Then, you can sort your list, do a IndexOf(Key1) and retrieve the object.

That way, your list is sorted and the search is very fast.

like image 37
vIceBerg Avatar answered Sep 30 '22 00:09

vIceBerg