Delphi TDictionary 迭代

24

我有一个函数,在其中存储了一些键值对,当我迭代它们时,我会两次收到这个错误:[dcc32 错误] App.pas(137): E2149 类没有默认属性。 以下是我的代码的一部分:

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;

我需要从字典中的每个项目收集信息。 我该怎么办?


3
var S: string; Pair: TPair<string, string>; begin // 遍历 YourDictionary 中的每个键值对,将其 Key 和 Value 拼接到字符串 S 上 for Pair in YourDictionary do S := S + Pair.Key + Pair.Value; end; - TLama
1
使用 for AKey in requestContent.Keys do begin request.Append(AKey + '=' + TIdURI.Encode(requestContent[AKey]) + '&'); ... etc.。当然,你必须将 AKey 声明为字符串。 - Rudy Velthuis
2
@RudyVelthuis 对于字典,最好的做法几乎总是遍历键值对而不是仅仅遍历键。这样做通常会导致更高效的代码。在 Delphi 字典的情况下,键值对迭代器避免了任何需要计算哈希码和执行探测的需求。 - David Heffernan
@David:我看到了你的答案并点赞了。我同意。起初我想到的解决方案最接近问题,但获取成对数据确实更好。 - Rudy Velthuis
1个回答

51
你的字典类的KeysValues属性类型分别为TDictionary<string, string>.TKeyCollectionTDictionary<string, string>.TValueCollection。这些类都是从TEnumerable<T>派生出来的,不能通过索引迭代。但是你可以迭代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迭代器更加高效。这是因为实现细节意味着pair迭代器能够在不进行以下操作的情况下迭代字典:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接