我有一个包含许多记录的数组。设置如下:
Tcustomer= record
Name: string[40];
Address: string[100];
phone: string[15];
email:string[50];
end;
现在,让我们说我想在这个数组中搜索具有某个名称和某个地址的人。我该怎么做?所以基本上只搜索1个元素。 (我可以搜索具体的1个属性,但不能过滤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;
要匹配值的组合(例如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.