delphi字典迭代

sou*_*her 1 delphi loops tdictionary

g'morning!

我填充一个字典TDictionary<String, TStringlist>(delphi-collections-unit),字符串作为值,几个字符串作为值.就像是:

  • 名字=约翰,丽莎,斯坦
  • 技能=读,写,说
  • 年龄= 12,14,16

(当然没有",").我需要的是迭代这个字典并用键乘以值.输出应该是这样的

  • names = john skills =读取年龄= 12
  • names = john skills =读取年龄= 14
  • names = john skills =读取年龄= 16
  • names =约翰技能=写年龄= 12
  • names =约翰技能=写年龄= 14
  • names =约翰技能=写年龄= 16
  • ...
  • names = lisa skills =读取年龄= 12
  • ...
  • names = stan skills = speak age = 16

所以每一个组合.我怎么能这样做?键的数量是动态的,tstringlist的大小也是动态的.谢谢!现在已经解决了......

现在问题的范围.以下是填写字典的程序.subsplits和splitstring是字符串列表,在过程结束时释放.在程序块之后创建了dict(在main中它是如何被调用的?),fill-method被调用然后我想像代码示例那样进行递归但是dict中没有值... .

while not Eof(testfile) do
  begin
    ReadLn(testfile, text);
    if AnsiContainsStr(text, '=') then
    begin
      Split('=', text, splitarray);
      splitarray[0] := trim(splitarray[0]);
      splitarray[1] := DeleteSpaces(splitarray[1]);
      if AnsiStartsStr('data', splitarray[0]) then
      begin
        split(' ', splitarray[0], subsplit1);
        splitarray[0]:=subsplit1[1];
        split(',', splitarray[1], subsplit2);
        dict.Add(splitarray[0], subsplit2);
        for ValueName in dict.Values do
        begin
          for i := 0 to Valuename.Count - 1 do
          write('Values are : '+ Valuename[i]);
        writeln;
        end;//
      end;//
    end;//
  end;//
Run Code Online (Sandbox Code Playgroud)

Cos*_*und 6

通过使用,你想要的东西有点复杂TDictionary<string, TStringList>,因为这意味着可变数量的键.如果它不是可变数量的键,您将不需要字典,并且您只需迭代3个TStringLists.

也就是说,你有经典的"产生所有排列"的问题.它可以使用递归或回溯来解决.递归更容易实现,回溯使用更少的堆栈空间.这是你的选择.这是一个完整的控制台应用程序,完成整个交易,从初始化字典,填充字典,使用递归函数生成所有排列.

program Project23;

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes, Generics.Collections;

var
  Dict:TDictionary<string, TStringList>;
  L: TStringList;
  KeyName: string;
  KeysList: TStringList;

// Help procedure, adds a bunch of values to a "Key" in the dictionary
procedure QuickAddToDict(KeyName:string; values: array of string);
var L: TStringList;
    s: string;
begin
  // Try to get the TStringList from the dictionary. If we can't get it
  // we'll create a new one and add it to the dictionary
  if not Dict.TryGetValue(KeyName, L) then
  begin
    L := TStringList.Create;
    Dict.Add(KeyName, L);
  end;
  // Iterate over the values array and add stuff to the TStringList
  for s in values do
    L.Add(s);
end;

// Recursive routine to handle one KEY in the dictionary
procedure HandleOneKey(KeyIndex:Integer; PrevKeys:string);
var L:TStringList;
    i:Integer;
    Part: string;
    KeyName: string;
begin
  KeyName := KeysList[KeyIndex];
  L := Dict[KeyName];
  for i:=0 to L.Count-1 do
  begin
    Part := KeyName + '=' + L[i];
    if KeyIndex = (KeysList.Count-1) then
      WriteLn(PrevKeys + ' ' + Part) // This is a solution, we're at the last key
    else
      HandleOneKey(KeyIndex+1, PrevKeys + ' ' + Part); // Not at the last key, recursive call for the next key
  end;
end;

begin
  try
    Dict := TDictionary<string, TStringList>.Create;
    try

      // Add whatever you want to the Dict.
      // Using the helper routine to set up the dictionary faster.
      QuickAddToDict('names', ['john', 'lisa', 'stan']);
      QuickAddToDict('skills', ['read', 'write', 'speak']);
      QuickAddToDict('ages', ['12', '14', '16']);

      // Extract all the keys to a string list. Unfortunately the dictionary
      // doesn't offer a way to get a key name by index, so we have to use the
      // keys iterator to extract all keys first.
      KeysList := TStringList.Create;
      try
        for KeyName in Dict.Keys do
          KeysList.Add(KeyName);
        if KeysList.Count > 0 then
        begin
          // We got at least one key, we can start the recursive process.
          HandleOneKey(0, '');
        end;
      finally KeysList.Free;
      end;

      WriteLn;
      WriteLn('Press ENTER to make the window go away');
      ReadLn;

    finally
      // TDictionary doesn't own the keys or the values. Strings are managed types in
      // delphi, we don't need to worry about them, but we do need to free the TStringList's
      // We use the Values iterator for that!
      for L in Dict.Values do
        L.Free;
      Dict.Free;
    end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
Run Code Online (Sandbox Code Playgroud)