简体   繁体   中英

Turn this if-then logic into a boolean expression?

I'm having a bit of a brain fart on making this code more concise(preferably a single boolean expression)

This is my code:

                    if (d.Unemployed)
                    {
                        if (type.Unemployed)
                        {
                            tmp.Unemployed = true;
                        }
                        else
                        {
                            tmp.Unemployed = false;
                        }
                    }
                    else
                    {
                        if (type.Unemployed)
                        {
                            tmp.Unemployed = false;
                        }
                        else
                        {
                            tmp.Unemployed = true;
                        }
                    }

Basically the point is that if either type or d is not unemployed, then tmp should be set to not unemployed.

How about:

tmp.Unemployed = type.Unemployed == d.Unemployed;

If we construct a truth table by following the code, we get

d  | type | tmp
---+------+----
1  |   1  |  1
---+------+----
1  |   0  |  0
----+-----+----
0  |   1  |  0
----+-----+----
0  |   0  |  1

The above is equivalent with the negation of the xor operation.

tmp = not (d xor type)

If the language doesn't have the xor operator we can use the != on boolean values.

tmp = ! (d != type);
// or
tmp = d == type;

Thinking about how much "brain fart" this caused you I would consider using a well named variable to avoid having to go through this mental process again in future. Something like this:

isTmpUnemployed = (type.Unemployed == d.Unemployed);
tmp.Unemployed = isTmpUnemployed;
tmp.Unemployed = d.Unemployed || type.Unemployed ? !tmp.Unemployed : null;

The above code means "both unemployed or both not unemployed". Thus, not (A xor B):

 tmp.Unemployed = ! ( D.Unemployed ^ type.Unemployed)

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