ima
ima

Reputation: 69

how to insert if else in equal statement

I need to set the condition as below code.

_orderStatus = Request.QueryString["order"] != null ? Request.QueryString["order"] : _orderStatus != "" ? _orderStatus : "pending";

Currently the condition only applied to show pending order. How can i change and add to get as below condtion:

if Request.QueryString["order"] != null then 
  _orderStatus: "pending"
else 
  _orderStatus: "confirmed"

Thanks

Upvotes: 2

Views: 212

Answers (4)

Ravi Kanth
Ravi Kanth

Reputation: 1210

There are multiple ways to do either u can simply check the for null or Empty by using if conditon like this

 if (!string.IsNullOrEmpty(Request.QueryString["order"]))
      _orderStatus = "pending";
else
     _orderStatus = "confirmed";

or you can use conditional expression For reference u can go through this link

For your question u can use this way

_orderStatus = Request.QueryString["order"] != null ? "pending" : "Confirmed";

There's no reason to expect any difference in performance.

In my opinion, the ternary operator should only be used if all three operands are very concise and easy to read. Otherwise I think it has the potential to make code harder to read.

I think a lot of people mis-use this operator by using too much logic into one long line of code. I personally won't use it unless the whole line is less than about 80 characters.

Upvotes: 0

sujith karivelil
sujith karivelil

Reputation: 29026

Additional note to the above answer: Let me copy your requirement to the answer:

if Request.QueryString["order"] != null then _orderStatus: "pending" else _orderStatus: "confirmed"

Here you need to assign the result to the variable _orderStatus, The conditional operator will do that for you, you need not to do an additional assignment within the operator.

While using conditional operator if.. then can be replaced with ? and else will be replaced by : and the result will be assigned to the _orderStatus.

Now look into your code( which included in the answer), and apply the replacements as i said. then you will get the answer like the following:

_orderStatus = Request.QueryString["order"] != null ? "pending" : "Confirmed";

Upvotes: 1

Nazir Ullah
Nazir Ullah

Reputation: 610

The bets way of checking your query string then, try this

  if (!string.IsNullOrEmpty(Request.QueryString["order"]))
          _orderStatus = "pending";
  else
         _orderStatus = "confirmed";

Upvotes: 0

Mark
Mark

Reputation: 2063

should be like this

_orderStatus = Request.QueryString["order"] != null ? "pending" : "Confirmed";

Upvotes: 5

Related Questions