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

I have many constants that are somehow connected, at some point I need to connect them, something like this:

const key1 = '1'; key2 = '2'; key3 = '3'; value1 = 'a'; value2 = 'b'; value3 = 'c'; 

I want to avoid:

 if MyValue = key1 then Result := value1; 

I know how to do this with string lists using:

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

But is there an easier way to do this?

+6
delphi
source share
3 answers

Yes, the assignment can be done this way, instead, avoiding the manual concatenation of strings:

 MyStringList.Values[Key1] := Value1; 
+9
source share

Wrap around your meaning

  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 IndexOf (Key1) and retrieve the object.

Thus, your list is sorted and the search is very fast.

+4
source share

You can use a multidimensional constant array with an enumeration for at least one of the dimensions:

Define this as follows:

 type TKVEnum = (tKey, tValue); // You could give this a better name const Count = 3; KeyValues: array [1..Count, TKVEnum] of string = // This is each of your name / value paris (('1', 'a'), ('2', 'b'), ('3', 'd')); 

Then you use it as follows:

 if MyValue = KeyValues[1, TKVEnum.tKey] then Result := KeyValues[1, TKVEnum.tValue] 

You can use the For loop. This is just as effective as their individual constant lines, but gives you the added advantage that they are related to each other.

Instead of defining the first dimension numerically, I would suggest

 type TConstPairs = (tcUsername, tcDatabase, tcEtcetera); 

But I think that it completely depends on what you imagine.

0
source share

All Articles