【问题标题】:Delphi TDictionary iterationDelphi TDictionary 迭代
【发布时间】:2014-09-29 12:22:55
【问题描述】:

我有一个存储一些键值对的函数,当我对它们进行迭代时,我得到了两次这个错误:[dcc32 Error] App.pas(137): E2149 Class does not have a default property。 这是我的代码的一部分:

function BuildString: string;
var
  i: Integer;
  requestContent: TDictionary<string, string>;
  request: TStringBuilder;
begin
  requestContent := TDictionary<string, string>.Create();

  try
    // add some key-value pairs
    request :=  TStringBuilder.Create;
    try
      for i := 0 to requestContent.Count - 1 do
      begin
        // here I get the errors
        request.Append(requestContent.Keys[i] + '=' +
          TIdURI.URLEncode(requestContent.Values[i]) + '&');
      end;

      Result := request.ToString;
      Result := Result.Substring(0, Result.Length - 1); //remove the last '&'
    finally
      request.Free;
    end; 
  finally
    requestContent.Free;
  end;
end;

我需要从字典中的每个项目中收集信息。我该如何解决?

【问题讨论】:

  • var S: string; Pair: TPair&lt;string, string&gt;; begin for Pair in YourDictionary do S := Pair.Key + Pair.Value; end;
  • 使用for AKey in requestContent.Keys do begin request.Append(AKey + '=' + TIdURI.Encode(requestContent[AKey]) + '&amp;'); ... etc.。当然,您必须将AKey 声明为字符串。
  • @RudyVelthuis 使用字典,迭代对比迭代键几乎总是更好。这样做总是会产生更高效的代码。在 Delphi 字典的情况下,pair 迭代器避免了计算哈希码和执行探测的任何需要。
  • @David:我看到了你的回答并 +1 编辑了它。我同意。我首先想到了一个最接近问题的解决方案,但获得对确实更好。

标签: delphi iteration tdictionary


【解决方案1】:

您的字典类的KeysValues 属性的类型分别为TDictionary&lt;string, string&gt;.TKeyCollectionTDictionary&lt;string, string&gt;.TValueCollection。这些类派生自TEnumerable&lt;T&gt;,不能通过索引进行迭代。但是,您可以迭代 Keys,或者实际上是 Values,并不是说执行后者对您有多大用处。

如果您对Keys 进行迭代,您的代码可能如下所示:

var
  Key: string;
....
for Key in requestContent.Keys do
  request.Append(Key + '=' + TIdURI.URLEncode(requestContent[Key]) + '&');

然而,这是低效的。既然你知道你想要键和匹配值,你可以使用字典的迭代器:

var 
  Item: TPair<string, string>; 
....
for Item in requestContent do 
  request.Append(Item.Key + '=' + TIdURI.URLEncode(Item.Value) + '&');

pair 迭代器比上面的第一个变体更有效。这是因为实现细节意味着对迭代器能够在没有以下情况下迭代字典:

  1. 计算每个键的哈希码,并且
  2. 在哈希码冲突时执行线性探测。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多