搜索已经放入delphi / lazarus中的记录数组的记录

时间:2014-04-01 23:12:07

标签: arrays delphi record pascal lazarus

我有一个包含许多记录的数组。设置如下:

Tcustomer= record
  Name: string[40];
  Address: string[100];
  phone: string[15];
  email:string[50]; 
end;

现在,让我们说我想在这个数组中搜索具有某个名称​​和某个地址的人。我该怎么做?所以基本上只搜索1个元素。 (我可以搜索具体的1个属性,但不能过滤1个以上)

附件是我的表单如何设置的图片,这将更详细地显示我所指的是什么:

enter image description here

1 个答案:

答案 0 :(得分:3)

您只需迭代数组并检查循环中记录的多个属性。以下是在姓名,地址,电话或电子邮件中搜索匹配项的示例;要更改它以在多个记录属性中查找匹配项(例如名称​​和地址),只需使用or替换测试中的and子句和两个或多个测试,如if (Customers[Idx].Name = Name) and (Customers[Idx].Address = Address) then

type
  TCustomer = record
    Name: string[40];
    Address: string[100];
    Phone: string[15];
    Email:string[50]; 
  end;

  TCustomerList: array of TCustomer;

function FindCustomer(const Name, Address, EMail,
  Phone: string; const Customers: TCustomerList): Integer;
var
  i: Integer;
begin
  Result := -1;                           // Value if no match found
  for i := Low(Customers) to High(Customers) do
  begin
    if (Customers[i].Name = Name) or        // Name matches?
       (Customers[i].Address = Address) or  // Address?
       (Customers[i].EMail = EMail) or      // Same email?
       (Customers[i].Phone = Phone) then    // Same phone
      begin
        Result := i;                        // Yep. We have a match.
        Exit;                               // We're done.
      end;
  end;
end;

样品使用:

var
  Idx: Integer;
begin
  // Customers is your array of TCustomer in a TCustomerList
  Idx := FindCustomer('', '', '', 'jsmith@example.com', Customers);
  if (Idx = -1) then
    WriteLn('No match found.')
  else
    WriteLn(Format('Customer %d: %s %s %s %s',
                   [Idx, 
                    Customers[Idx].Name,
                    Customers[Idx].Address,
                    Customers[Idx].Phone,
                    Customers[Idx].EMail]));
end;

要匹配值的组合(例如NameAddress),只需适当更改if中的条件:

function FindCustomerByNameAndAddress(const Name, Address: string; 
  const Customers: TCustomerList): Integer;
var
  i: Integer;
begin
  Result := -1;                           // Value if no match found
  for i := Low(Customers) to High(Customers) do
  begin
    if (Customers[i].Name = Name) then          // Name matches.
      if (Customers[i].Address = Address) then  // Does address?
      begin
        Result := i;                            // Yep. We found it
        Exit;                               
      end;
  end;
end;

样品使用:

Idx := FindCustomerByNameAndAddress('John Smith', '123 Main Street`);
if Idx = -1 then
  // Not found
else
  // Found. Same code as above to access record.