简体   繁体   English

Delphi TDictionary迭代

[英]Delphi TDictionary iteration

I have a function where I store some key- value pairs and when I iterate them I get this error twice: [dcc32 Error] App.pas(137): E2149 Class does not have a default property. 我有一个函数,我存储一些键值对,当我迭代它们时,我得到两次错误:[dcc32错误] App.pas(137):E2149类没有默认属性。 Here is part of my code: 这是我的代码的一部分:

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;

I need to collect the information from each item in the dictionary. 我需要收集字典中每个项目的信息。 How can I fix it? 我该如何解决?

The Keys and Values properties of your dictionary class are of type TDictionary<string, string>.TKeyCollection and TDictionary<string, string>.TValueCollection respectively. 字典类的KeysValues属性的类型分别为TDictionary<string, string>.TKeyCollectionTDictionary<string, string>.TValueCollection These classes are derived from TEnumerable<T> and cannot be iterated by index. 这些类派生自TEnumerable<T> ,不能通过索引进行迭代。 You can however iterate over Keys , or indeed Values , not that doing the latter would be of much use to you. 但是,你可以迭代Keys ,或者确实是Values ,而不是后者对你有用。

If you iterated over Keys your code might look like this: 如果您遍历Keys您的代码可能如下所示:

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

This however is inefficient. 然而,这是低效的。 Since you know that you want both key and matching value, you can use the dictionary's iterator: 既然你知道你想要键和匹配值,你可以使用字典的迭代器:

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

The pair iterator is more efficient than the first variant above. 对迭代器比上面的第一个变量更有效。 This is because the implementation details mean that the pair iterator is able to iterate the dictionary without: 这是因为实现细节意味着对迭代器能够迭代字典而不需要:

  1. Calculating hash codes for each key, and 计算每个密钥的哈希码,和
  2. Performing linear probing when hash codes collide. 当哈希码发生冲突时执行线性探测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM