delphi Using records as key in TDictionary

后端 未结 3 777
春和景丽
春和景丽 2021-02-05 13:38

Can you use a record as a Key value in TDictionary? I want to find objects based on combination of string, integer and integer.

TUserParKey=record
  App:string;
         


        
相关标签:
3条回答
  • 2021-02-05 14:04

    My best approach should be to joint the default hash code of the base types.

    For instance:

    Value.App.GetHashCode + Value.ID.GetHashCode + Value.Nr.GetHashCode;
    
    0 讨论(0)
  • 2021-02-05 14:05

    Yes, you can use records as keys in a TDictionary but you should provide your own IEqualityComparer when creating the dictionary because the default one for records just does a dumb binary compare of the record. This fails for a record containing a string because it just compares the pointer of that string which may be different even if the string contains the same value.

    Such a comparer would look like this:

    type
      TUserParKeyComparer = class(TEqualityComparer<TUserParKey>)
        function Equals(const Left, Right: TUserParKey): Boolean; override;
        function GetHashCode(const Value: TUserParKey): Integer; override;
      end;
    
    function TUserParKeyComparer.Equals(const Left, Right: TUserParKey): Boolean;
    begin
      Result := (Left.App = Right.App) and (Left.ID = Right.ID) and (Left.Nr = Right.Nr);
    end;
    
    function TUserParKeyComparer.GetHashCode(const Value: TUserParKey): Integer;
    begin
      Result := BobJenkinsHash(PChar(Value.App)^, Length(Value.App) * SizeOf(Char), 0);
      Result := BobJenkinsHash(Value.ID, SizeOf(Integer), Result);
      Result := BobJenkinsHash(Value.Nr, SizeOf(Integer), Result);
    end;
    
    0 讨论(0)
  • 2021-02-05 14:18

    Instead of using the record as a key, you could use a string consisting of the serialized record. You could use something like https://github.com/hgourvest/superobject to do the serialization.

    Since strings have built-in comparison semantics and hashcodes, you don't need to write comparison and hashcode functions.

    0 讨论(0)
提交回复
热议问题