Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternative to check, whether a value is in a set

Tags:

set

delphi

I have the following code. It looks ugly, if the value equals to one of the following value then do something.

var
  Value: Word;
begin
  Value := 30000;
  if (Value = 30000) or (Value = 40000) or (Value = 1) then
    do_something;
end;

I want to refactor the code as follows:

var
  Value: Word;
begin
  Value := 30000;
  if (Value in [1, 30000, 40000]) then // Does not work
    do_something;
end;

However, the refactored code does not work. I assume that a valid set in Delphi accepts only elements with type byte. If there any good alternative to refactor my original code (besides using case)?

like image 419
stanleyxu2005 Avatar asked Jun 07 '10 07:06

stanleyxu2005


2 Answers

I think something like this?

case value of
  1, 30000, 40000: do_somthing
end;
like image 116
R-D Avatar answered Sep 21 '22 23:09

R-D


How about using an open array?

function ValueIn(Value: Integer; const Values: array of Integer): Boolean;
var
  I: Integer;
begin
  Result := False;
  for I := Low(Values) to High(Values) do
    if Value = Values[I] then
    begin
      Result := True;
      Break;
    end;
end;

Example (pseudo-code):

var
  Value: Integer;
begin
  Value := ...;
  if ValueIn(Value, [30000, 40000, 1]) then
    ...
end;
like image 20
Ondrej Kelle Avatar answered Sep 22 '22 23:09

Ondrej Kelle