user124784
user124784

Reputation: 956

C#: Choosing operator depending on boolean value (in one line)

I'm trying to get away with a slick one liner as I feel it is probably possible.

I'll put my code below and then try to explain a little more what I'm trying to achieve.

        for (int p = 0; p < 2; p++)
        {
            foreach (string player in players[p])
            {
                if (PlayerSkills[player].streak_count *>* 0) //This line
                    PlayerSkills[player].streak_count++;
                else
                    PlayerSkills[player].streak_count = 0;
            }
        }

*(p==0 ? >:<) the comparison operator is chosen depending on p.

Of course what I've written is rubbish. But basically I want to use >0 when p==0, and <0 when p>>0. Is there a nice way to achieve this?

Upvotes: 1

Views: 407

Answers (3)

Jay
Jay

Reputation: 3355

p > 0 ? whenGreaterThanZero : whenZeroOrLess ;

E.g.

int p = 1; bool test = p > 0 ? true : false ;

Lets test = True

Upvotes: 0

D Stanley
D Stanley

Reputation: 152566

Well, you should use what is most readable, even if it is not as consice. That said...

// Invert the count for all but the first player and check for a positive number
if (PlayerSkills[player].streak_count * (p==0 ? 1 : -1) > 0)

Upvotes: 10

BradleyDotNET
BradleyDotNET

Reputation: 61349

I don't know about slick, but the following and/or combination is one line:

if ((p == 0 && PlayerSkills[player].streak_count > 0)
     || PlayerSkills[player].streak_count < 0)
...

This will only ever do the array index once (due to the p==0 condition occurring first) and so is equivalent to the "ternary" you wrote (albeit a bit more verbose).

Upvotes: 4

Related Questions