use*_*431 0 arrays delphi pascal record lazarus
我有一个包含许多记录的数组。像这样设置:
Tcustomer= record
Name: string[40];
Address: string[100];
phone: string[15];
email:string[50];
end;
Run Code Online (Sandbox Code Playgroud)
现在,假设我想在这个数组中搜索具有特定姓名和地址的人。我该怎么办?所以基本上搜索不仅仅是1个元素。(我可以专门搜索 1 个属性,但不能过滤超过 1 个)
附件是我的表单如何设置的图片,这将更详细地显示我所指的内容:

您只需迭代数组并检查循环中记录的多个属性。这是一个在姓名、地址、电话或电子邮件中搜索匹配项的示例;要将其更改为在多个记录属性(如名称和地址)中查找匹配项,只需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;
Run Code Online (Sandbox Code Playgroud)
样品用途:
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;
Run Code Online (Sandbox Code Playgroud)
要匹配值的组合(例如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;
Run Code Online (Sandbox Code Playgroud)
样品用途:
Idx := FindCustomerByNameAndAddress('John Smith', '123 Main Street`);
if Idx = -1 then
// Not found
else
// Found. Same code as above to access record.
Run Code Online (Sandbox Code Playgroud)