Filip Sulik
Filip Sulik

Reputation: 129

How do I check whether an array contains a particular value?

how do I correctly write this ?:

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

where number is an integer and array is an array of integers from 1 to x

Upvotes: 3

Views: 37807

Answers (3)

Gabriel
Gabriel

Reputation: 71

I had the same question and solved it like this:

if value in myArray then
  ...

But as I needed to compare with specific values, I simply did:

if value in [0, 1, 2, 3] then
  ...
 

Upvotes: 7

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108929

I believe you want to do something if number is not found in the array MyArray. Then you can do it like this:

NoMatch := True;
for i := Low(MyArray) to High(MyArray) do
  if MyArray[i] = number then
  begin
    NoMatch := False;
    Break;
  end;

if NoMatch then
  DoYourThing;

You could create a function that checks if a number is found in an array. Then you can use this function every time you need to perform such a check. And each time, the code will be more readable. For example, you could do it like this:

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;

If you use a old version of Delphi, you have to replace Exit(True) with begin Result := True; Exit; end. In newer versions of Delphi, I suppose you could also play with stuff like generics.

Upvotes: 15

Alister
Alister

Reputation: 6837

You could also write a Generic version, however you can't use generics with stand-alone procedures, they need to be bound to a class or record. Something like the following

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.

usage would be

procedure TForm6.Button1Click(Sender: TObject);
begin
  if TArrayUtils<integer>.Contains(3, [1,2,3]) then
    ShowMessage('Yes')
  else
    ShowMessage('No');
end;

Should work with parameters like TArray<integer> or array of integer as well as constant arrays (shown) - and you could add many other methods to the class, such as IndexOf or Insert...

From Delphi 10.3 you can omit the <integer> due to type inferencing so would look like TArrayUtils.Contains(3, [1,2,3]).

Upvotes: 6

Related Questions