title: Delphi - access class string property by its value
body: <p>I have a class defined which contains only strings as properties, and I need to get the property name based on its value as in the example below. In the example there are only 3 properties, in the real life class there are almost 1000. The problem is that this class is heavily used, and I want to know if I can get the property name by its value in a faster way. </p>
  
  <pre><code>unit Unit5;
  
  interface
  
  uses
    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
    Dialogs,RTTI, StdCtrls, Diagnostics;
  
  type
    TConstDBElem = class
    public
      CCFN_1 : String;
      CCFN_2 : String;
      CCFN_3 : String;
      constructor Create;
    end;
  
    TForm5 = class(TForm)
      Memo1: TMemo;
      Button1: TButton;
      procedure Button1Click(Sender: TObject);
    end;
  
  var
    Form5: TForm5;
    Obj: TConstDBElem;
  
  implementation
  
  
  {$R *.dfm}
  
  procedure TForm5.Button1Click(Sender: TObject);
  var iPos:Integer;
      timer:TStopwatch;
      Function GetName(const DBElemInstance : TConstDBElem; valueName: string) : string;
    var
      vrttiContext: TRttiContext;
      vrttiField : TRttiField;
      vType : TRttiType;
    begin
        vType := vrttiContext.GetType(TConstDBElem);
  
        for vrttiField in vType.GetFields do
          if (vrttiField.GetValue(DBElemInstance).ToString = valueName) then
          begin
             result := vrttiField.Name;
           end;
    end;
  
  begin
    timer := TStopwatch.Create;
    timer.Start;
    Memo1.Lines.Clear;
    for iPos := 0 to 100000 do
      GetName(Obj,'TEST3');
    timer.Stop;
    Memo1.Lines.Add(FloatToStr(timer.Elapsed.TotalSeconds));
  end;
  
  constructor TConstDBElem.Create;
  begin
    CCFN_1 := 'TEST1';
    CCFN_2 := 'TEST2';
    CCFN_3 := 'TEST3' ;
  end;
  
  initialization
    Obj := TConstDBElem.Create;
  
  finalization
    Obj.Free;
  
  
  end.
  </code></pre>
  
  <p>Yes,I know this is a very bad design, and this should not be done like this. Is there any option to make this search faster?</p>