Главная страница | назад





Article #22114: How to use sets in code, such as adding to TDBGrid.Options, at run time

Question: I know how to use the object inspector to change the value of a set, such as TDBGrid.Options, but how do I manipulate sets in code?

Answer: To use sets, you will have to use square brackets to refer to set elements. Sets can have at most 256 elements in them. Here is an example of using and declaring sets:

Sample Code

type
// Here are some examples of declaring set types.
  // A variable of TMyMonth can take one and only one of
  // one of its members.
  TMyMonth = (Jan, Feb, Mar, Apr, May);
  // TMyMonthSet can be an empty set (no months in it), or
  // contain any combination of the above months.
  TMyMonthSet = set of TMyMonth;
  // TMySubMonthSet is a subset of the above set, only able
  // to take on the first 3 months
  TMySubMonthSet = set of Jan..Mar;

  // TMyIntSet can be an empty set, or any combination of integers
  // in the range of 1 to 15.
  TMyIntSet = set of 1..15;
  // TMySubIntSet can be an empty set, or any combination of integers
  // in the range of 1 to 5.
  TMySubIntSet = set of 1..5;

// Here are some examples of declaring set variables 
var
  MyMonth: TMyMonth; // can only be one month (NOT a set)
  MyMonthSet: TMyMonthSet; // can be more than one month
  MyIntSet: TMyIntSet; // can be a combination of ints from 1 to 15 only
begin
  // The TMyMonth type can only take on one value at a time
  MyMonth := May;

  // Sets can take on more than one value, and notice the use of square
  // brackets
  MyMonthSet := [Jan, Mar, May];
  // MySubMonths can only take the values Jan..Mar. If you try to set it
  // to May, you won't get a compile time error, but the set will be empty.

  MyIntSet := [20]; // 20 is past the range for the set..so this should do nothing!
  if MyIntSet = [] then
    ShowMessage('MyIntSet is empty! (as expected...)');

  // Here are some common operations you can do with sets:
  // + Union operator
  MyMonthSet := MyMonthSet + [Feb, Apr]; // Add 2 months to the set
  // - Difference operator
  MyMonthSet := MyMonthSet - [MyMonth]; // Remove May from the set
  MyMonthSet := MyMonthSet - [Jan..Apr]; // Remove Jan through Apr
  // The set should now be empty (use the equality operator = to test sets)
  if MyMonthSet = [] then
    ShowMessage('MyMonthSet is empty! (as expected...)');

  // * Intersection operator
  MyMonthSet := [Jan, Feb] * [Jan, Apr];
  if MyMonthSet = [Jan] then
    ShowMessage('MyMonthSet is Jan! (as expected...)');

  // <= Subset operator
  if [Jan, Apr] <= [Jan..Apr] then
    ShowMessage('[Jan, Apr] <= [Jan..Apr], as expected...');
  // <= Subset operator is the opposite of the above

  // To test if an ordinal is in the set, us the "in" operator
  if Jan in [Jan..Feb] then
    ShowMessage('Jan in set [Jan..Feb]');
end.

Last Modified: 31-MAY-00