简体   繁体   中英

How I know the index of specific value in a set

I have these codes:

    TAPPUGroup = (APP_UG_USERS, APP_UG_SUPER_USERS, APP_UG_ADMINS);
    TAPPUGroups = set of TAPPUGroup;

    TAppUser = record
        UID: integer;
        UName: string;
        UGroup: TAPPUGROUPS;

    end;

...
LoggedUser: TAppUser;

I used include to add groups to LoggedUser.UGroup, now how I know the index of specific value in TAPPUGroup for example if APP_UG_SUPER_USERS included in LoggedUser.UGroup how I can get it's index in TAPPUGroup ?

Example: If LoggedUser.UGroup = APP_UG_SUPER_USERS then I want to return 1 if LoggedUser.UGroup = APP_UG_ADMINS I want to return 2 and so on.

If you really do want the index of a given enumeration item in the enumeration, all you need to do is just use Ord().

To go the other way, you can use the enumeration name as it it were a function:

AGroup := TAPPUGroup(1);

Anyway, Ord() is how you find the index of a given enumeration value (like APP_UG_USERS) in a contiguous enumeration declaration. To find out whether a particular set instance contains a given set element, ou use the "if xxx in ..." construct Remy shows, eg

if APP_UG_USERS in MySet then  ...

You can also do this

var 
  AValue : TAPPUGroup;
  MySet : TAPPUGroups ;

for AValue:= Low(TAPPUGroup) to High(TAPPUGroup) do
  if AValue in MySet then ...

You don't need the index. To know if a value exists in the Set, use the in operator instead:

if APP_UG_SUPER_USERS in LoggedUser.UGroup then

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM