Although LU RD showed a direct solution to your question, I'm going to add a slightly different generic approach. This has the advantage of providing the right solution for different types of arrays in one place.
In versions of Delphi that support generics, you can use the method used in TArray, found in System.Generics.Collections. This is a direct extension of this class introducing the IndexOf function:
type TArrayExt = class(TArray) public class function IndexOf<T>(const Values: array of T; const Item: T; const Comparer: IEqualityComparer<T>; Index, Count: Integer): Integer; overload; static; class function IndexOf<T>(const Values: array of T; const Item: T; const Comparer: IEqualityComparer<T>): Integer; overload; static; class function IndexOf<T>(const Values: array of T; const Item: T): Integer; overload; static; end; class function TArrayExt.IndexOf<T>(const Values: array of T; const Item: T; const Comparer: IEqualityComparer<T>; Index, Count: Integer): Integer; var I: Integer; begin if (Index < Low(Values)) or ((Index > High(Values)) and (Count > 0)) or (Index + Count - 1 > High(Values)) or (Count < 0) or (Index + Count < 0) then raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange); if Count = 0 then begin Exit(-1); end; for I := Index to Index + Count - 1 do begin if Comparer.Equals(Item, Values[I]) then begin Exit(I); end; end; Result := -1; end; class function TArrayExt.IndexOf<T>(const Values: array of T; const Item: T; const Comparer: IEqualityComparer<T>): Integer; begin Result := IndexOf<T>(Values, Item, Comparer, Low(Values), Length(Values)); end; class function TArrayExt.IndexOf<T>(const Values: array of T; const Item: T): Integer; begin result := IndexOf<T>(Values, Item, TEqualityComparer<T>.Default, Low(Values), Length(Values)); end;
A simple use case might look like this:
procedure Main; var arr: TArray<Integer>; N: Integer; begin arr := TArray<Integer>.Create(5, 7, 3, 4, 2); repeat Readln(N); N := TArrayExt.IndexOf(arr, N); Writeln(N); until false; end;
source share