【问题标题】:What type of collection should I use? delphi我应该使用什么类型的集合?德尔福
【发布时间】:2017-12-31 19:07:42
【问题描述】:

我想在 Delphi 中对两个值使用一个键,就像这样

TDictionary<tkey, tfirstvalue,tsecondvalue>;

【问题讨论】:

  • 是什么阻止您使用元组作为键?
  • 在 c# netfram 4 中使用,但我想在 delphi 中使用
  • 使用 dynarray 作为键的值怎么样?还是有两个值的记录?然后它变成了类似于TDictionary&lt;TKey, TRecordContainingFirstAndSecondValue&gt; 的东西,这应该是可行的。或使用 TPair&lt;TFirstValue, TSecondValue&gt; 作为值类型(无论如何都相当于 2 类型记录)。
  • @DavidStockinger:Delphi 没有内置元组。可以使用其他可用的数据类型轻松模拟它们,但它们不作为内置类型存在。
  • 换句话说,这些值可以很容易地以多种方式组合为一种类型(包含多个值)。 TValue 部分可以任意大,因此可以有 1:1 和 1:many 关系。如果你想拥有不同的键类型,或者每个值有多个键(many:many),或者类似的,它只会变得毛茸茸,因为 TDictionary 不是为此而设计的。

标签: delphi key tdictionary


【解决方案1】:

将您的价值观放入像记录一样的复合结构中。然后将该记录类型用作您的字典值类型。

【讨论】:

    【解决方案2】:

    Delphi 没有 Tuple 类型。 我不知道你的目的,但记录类型的动态数组可能会有所帮助。

    Type
    Tdict_ = reocord
     tkey:integer;
    tfirstvalue,Tsecondvalue :string;
    end;
    var
    Tdict:array of tdict_
    ...
    procedure adddata(Tkey:integer;tfirstvalue:string;Tsecondvalue :string); 
    begin
         setlength(tdict,length(tdict)+1);
        tdict[length(tdict)-1].tkey:=tkey;
        tdict[length(tdict)-1].tfirstvalue:=tfirstvalue;
        tdict[length(tdict)-1].tsecondtvalue:=tsecondvalue;    
    end;
    

    但你必须为数组的返回索引编写自己的“查找”函数。

    例如

        Function find(tkey:integer):integer;
        var i:Integer;
        begin
         for i:=0 to length(Tdict)-1 do
         if tdict[i].tkey=i then
           begin
            result:=i;
            break;
           end;
        end;
    
        Function deletecalue(tkey:integer):integer;
        var i,j:Integer;
        begin
         i:=find(tkey)
            for j:=i to length(Tdict)-2 do
               tdict[j]:=tdict[j+1];
            setlength(tdict,length(tdict)-1);
    
        end;
    

    如果键是字符串类型必须更改,但是对于大日期会很慢。

    另请阅读: https://github.com/malcolmgroves/generics.tuples

    【讨论】:

      【解决方案3】:

      TDictionary&lt;TKey, TPair&lt;TFirstValue, TSecondValue&gt;&gt;,正如 @RudyVelthuis 评论的那样,是可能的并且有效。但是,TPair(可在 System.Generics.Collections 中找到)并不是为此而设计的 - 这两个值分别命名为 KeyValue,这在这里没有意义。我们应该复制一份TPair,可以命名为TTuple

      然后你就可以MyDictionary.Add('key', TTuple&lt;string, string&gt;.Create('firstvalue', 'secondvalue'));

      由于它是作为record值类型)实现的,所以不需要释放它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-01
        • 1970-01-01
        • 2014-07-08
        • 1970-01-01
        • 1970-01-01
        • 2013-01-15
        • 1970-01-01
        • 2022-07-12
        相关资源
        最近更新 更多