小数据量的Key-Value查找类的实现

平时写程序时经常要把一些Key与Value保存起来,但一般数据量都不大,故不想用TStringHash来做。而用TStringList来做,还要写一个"=",挺别扭!而且数据类型还有限制。自己从VCL中找了一段,感觉挺好用的,以后用它玩一玩!不过对Key值的搜索采用遍历方式,数据量大就慢了,建议采用HashTable。

注:Key与Value均不受数据类型限制!

 

TLookupList = class(TObject)

  private

    FList: TList;

  public

    constructor Create;

    destructor Destroy; override;

    procedure Add(const AKey, AValue: Variant);

    procedure Clear;

    function ValueOfKey(const AKey: Variant): Variant;

  end;

{ TLookupList }

constructor TLookupList.Create;

begin

  FList := TList.Create;

end;

destructor TLookupList.Destroy;

begin

  if FList <> nil then Clear;

  FList.Free;

end;

procedure TLookupList.Add(const AKey, AValue: Variant);

var

  ListEntry: PLookupListEntry;

begin

  New(ListEntry);

  ListEntry.Key := AKey;

  ListEntry.Value := AValue;

  FList.Add(ListEntry);

end;

procedure TLookupList.Clear;

var

  I: Integer;

begin

  for I := 0 to FList.Count - 1 do

    Dispose(PLookupListEntry(FList.Items[I]));

  FList.Clear;

end;

function TLookupList.ValueOfKey(const AKey: Variant): Variant;

var

  I: Integer;

begin

  Result := Null;

  if not VarIsNull(AKey) then

    for I := 0 to FList.Count - 1 do

      if PLookupListEntry(FList.Items[I]).Key = AKey then

      begin

        Result := PLookupListEntry(FList.Items[I]).Value;

        Break;

      end;

end;
View Code

 

 

测试

 

var

  Demo:TLookupList;

begin

  Demo:=TLookupList.Create;

  try

    Demo.Add('aa','bbb');

    ShowMessage(Demo.ValueOfKey('aa'));

  finally

    Demo.Free;

  end;

end;
View Code

 

你可能感兴趣的:(key-value)