How to turn if, else if logic into a ternary operator?

后端 未结 6 1819
执念已碎
执念已碎 2020-12-28 20:12

I was just wondering if this was possible because i started using ternary operators to reduce lines of code and i am loving it.

if (x==y)
{
    z += x;
} els         


        
相关标签:
6条回答
  • 2020-12-28 20:40

    you should do this by using parentheses like this:

    (x==y)?(z+=x):((x==z)?(z+=y):(z+=1))
    
    0 讨论(0)
  • 2020-12-28 20:45

    Four lines of code, and the most readable, IMO. No need for a ternary operator here:

    if (x == y || x == z)
        z += y;
    else 
       z++;    
    

    If I had to write it using ternary, I would do:

    z += (x == y || x == z) ? y : 1;
    
    0 讨论(0)
  • 2020-12-28 20:45

    To turn the z calculation into one line, I would do something like this:

    public int GetZBasedOnXY(int z, int x, int y)
    {
        // Chose this solution, but any can go in here and work.
        if (x == y || x == z)
            return z + y;
        else 
            return z + 1;
    }
    

    Then:

    z = GetZBasedOnXY(z, x, y);
    

    More readable, and if the naming is good and the method has unit test coverage, even better.

    0 讨论(0)
  • 2020-12-28 20:46

    This is simple to continue with ternary operator rather than if else if condition, just need to continue the same even after ":". below is the sample.

    var result = a ? x : b ? y : z;
    

    Reference example

    0 讨论(0)
  • 2020-12-28 20:53

    It would be like this:

    z =
      x == y ? z + x :
      x == z ? z + y :
      z + 1;
    

    If you use z += x as an operand it will end up doing z = (z += x). While it works in this special case, as the result of the expression z += x is the final value of z, it may not work in other cases.

    Howver, as all operations have the z += in common, you can do like this:

    z +=
      x == y ? x :
      x == z ? y :
      1;
    

    Use with care, though. The code is often more readable and maintainable the simpler it is, and nested conditional operations are not very readable. Also, use this only when you have an expression as the result of the conditional operation, it's not a drop-in replacement for the if statement.

    0 讨论(0)
  • 2020-12-28 21:00

    You can use

    z += x == y ? x : x == z ? y : 1;
    

    But honestly, that's not really more readable than what you had before. You can make it slightly clearer by adding parentheses:

    z += x == y ? x : (x == z ? y : 1);
    

    But generally I'd stay away from nested conditional operators unless when golfing.

    0 讨论(0)
提交回复
热议问题