Delphi 如何检查数组是否包含特定值?

Delphi 如何检查数组是否包含特定值?,delphi,Delphi,我如何正确地写这个 If number is different from Array[1] to Array[x-1] the begin...... 其中number是一个整数,array是一个从1到x的整数数组如果在数组MyArray中找不到number,我相信您需要做些什么。然后你可以这样做: NoMatch := true; for i := Low(MyArray) to High(MyArray) do if MyArray[i] = number then begin

我如何正确地写这个

If number is different from Array[1] to Array[x-1] the begin...... 

其中number是一个整数,array是一个从1到x的整数数组

如果在数组MyArray中找不到number,我相信您需要做些什么。然后你可以这样做:

NoMatch := true;
for i := Low(MyArray) to High(MyArray) do
  if MyArray[i] = number then
  begin
    NoMatch := false;
    break;
   end;

if NoMatch then
  DoYourThing;
function IsNumberInArray(const ANumber: integer; 
  const AArray: array of integer): boolean;
var
  i: integer;
begin
  for i := Low(AArray) to High(AArray) do
    if ANumber = AArray[i] then
      Exit(true);
  result := false;
end;

...

if not IsNumberInArray(number, MyArray) then
  DoYourThing;
您可以创建一个函数来检查数组中是否有数字。然后,您可以在每次需要执行此类检查时使用此功能。每一次,代码都会更具可读性。例如,您可以这样做:

NoMatch := true;
for i := Low(MyArray) to High(MyArray) do
  if MyArray[i] = number then
  begin
    NoMatch := false;
    break;
   end;

if NoMatch then
  DoYourThing;
function IsNumberInArray(const ANumber: integer; 
  const AArray: array of integer): boolean;
var
  i: integer;
begin
  for i := Low(AArray) to High(AArray) do
    if ANumber = AArray[i] then
      Exit(true);
  result := false;
end;

...

if not IsNumberInArray(number, MyArray) then
  DoYourThing;

如果使用旧版本的Delphi,则必须将Exittrue替换为begin result:=true;打破终止在较新版本的Delphi中,我想您也可以使用泛型之类的东西。

您也可以编写泛型版本,但是您不能将泛型用于独立的过程,它们需要绑定到类或记录。类似于下面的内容

unit Generics.ArrayUtils;

interface

uses
  System.Generics.Defaults;

type
  TArrayUtils<T> = class
  public
    class function Contains(const x : T; const anArray : array of T) : boolean;
  end;

implementation

{ TArrayUtils<T> }

class function TArrayUtils<T>.Contains(const x: T; const anArray: array of T): boolean;
var
  y : T;
  lComparer: IEqualityComparer<T>;
begin
  lComparer := TEqualityComparer<T>.Default;
  for y in anArray do
  begin
    if lComparer.Equals(x, y) then
      Exit(True);
  end;
  Exit(False);
end;

end.
用法将是

procedure TForm6.Button1Click(Sender: TObject);
begin
  if TArrayUtils<integer>.Contains(3, [1,2,3]) then
    ShowMessage('Yes')
  else
    ShowMessage('No');
end;
应该可以使用TArray或integer数组等参数以及所示的常量数组,并且可以向类中添加许多其他方法,例如IndexOf或Insert


从Delphi 10.3中,您可以省略由于类型推断而导致的结果,因此看起来像TArrayUtils.Contains3[1,2,3]。

我肯定建议您不要使用基于1的数组索引。请允许我重复这个建议。另外,数组在Delphi中不是有效的变量名。@AndreasRejbrand我以前也至少告诉过Filip一次:@DavidHeffernan:我相信Filip会注意到,当他试图编译代码时……请创建一个函数来检查数组中是否包含项。例如,在我的代码库中,我会写:如果不是TArray.Containsarr,那么值…@Jens,除了你的代码与Andreas的TArray需要的东西非常不同之外,这非常有效。非常感谢。似乎比安德烈亚斯的版本慢。