您只需迭代数组并检查循环中记录的多个属性。这是一个在姓名、地址、电话或电子邮件中搜索匹配项的示例;要将其更改为在多个记录属性中查找匹配项(如名称 和 地址),只需将测试中的 or 子句替换为使用 and 的两个或多个测试,如 @ 987654323@.
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;
要匹配值的组合(例如Name 和Address),只需适当更改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.