2
votes

I want to return a enum value based on a field value.

For example:

If Free value field has the value '15', I want to return the enum value "1", because the Label of enum value 1 is: '10-20', because 15 is in the range of 10-20 I want to return that value.

I want to create a display method for this.

I guess I can accomplish this with a switch case scenario.
How can I best set this up?

3

3 Answers

3
votes

Of course you can do it with a switch / case but if you deal with a range of values and a limited set of result values (your enumeration elements) then a simple if / else if is probably better suited

So instead of stating each possible value (1, 2, 3, 4 bla bla) in your case branches do something like this

int x;
;

x = yourTable.YourField;
if (x >= 1 && x <= 15)
{
    return YourEnum::1to15;
}
else if (x >= 16 && x <= 20)
{
    return YourEnum::16to20;
}
// other possible ranges
else
{
    throw YourEnum::Unknown;
}
1
votes

yes, with a switch statement you can do it.

Try this:

int value;

;

switch (value)
{       
    case 1, 2, 3, 4 ,5:
        //Your code
        break;

    case 10, 11, 12, 13, 14, 15, 16, 17, 18 ,19, 20 :
        //Your code
        break;                    

    default :            
        //Your code
}
1
votes

I personally like the idea of getting clever with integer division.

If your ranges are going to be groups of 10, then you can just divide by 10 to get to the enum value.

So see this code and screenshot below:

static void Job1(Args _args)
{
    int         i;
    MyEnum      value;

    // Test #1
    i       = 15;           // Your number
    value   = (i/10);       // Enum result
    info(strFmt("Test #1: %1", value));

    // Test #2
    i       = 5;           // Your number
    value   = (i/10);       // Enum result
    info(strFmt("Test #2: %1", value));

    // Test #3
    i       = 22;           // Your number
    value   = (i/10);       // Enum result
    info(strFmt("Test #3: %1", value));
}

enter image description here