Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition in Conditional (Ternary) Operator

How can I implement this using ternary operator?

if(UnitType == null)
{
    a = ElevationType
}
else
{
    a = UnitType
}

Ternary operator

a = UnitType == null ? ElevationType : UnitType;

Now I want something like this

if(UnitType == null)
{
   if(ElevationType == null)
   {
    a = StructureType
   }
   else{
    a = ElevationType
   }
}
else
{
    a = UnitType
}

Can I achieve this using ternary operator? If not, what should be done?

like image 859
zaria khan Avatar asked Oct 27 '16 13:10

zaria khan


People also ask

Can we use if condition in ternary operator?

Yes you can. A ternary conditional operator is an expression with type inferred from the type of the final two arguments. And expressions can be used as the conditional in an if statement.

Can ternary operator have two conditions?

In the above syntax, we have tested 2 conditions in a single statement using the ternary operator. In the syntax, if condition1 is incorrect then Expression3 will be executed else if condition1 is correct then the output depends on the condition2.

What is the condition for and operator?

The logical AND ( && ) operator (logical conjunction) for a set of boolean operands will be true if and only if all the operands are true . Otherwise it will be false .

How do you use if condition?

Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it's false. For example: =IF(A2>B2,"Over Budget","OK") =IF(A2=B2,B4-A4,"")


1 Answers

a = (UnitType == null) ? (ElevationType ?? StructureType) : UnitType;

But I stand by my comment: this is harder to understand than the if-else would be.

Or, possibly,

a = UnitType ?? ElevationType ?? StructureType;

That's reasonably clear if you're familiar with the ?? operator.

like image 92
Ann L. Avatar answered Sep 28 '22 08:09

Ann L.