user3198688
user3198688

Reputation: 305

Ternary operator with more than 1 condition check

I have a scenario where in order to assign a value to a variable I need to check more than 1 condition, is it possible to chain the conditions.

Below is just a sample format how my code looks

Result = (isUser == true && (ResultId == 1 || ResultId == 2 )) ? "Pass" : r.Result,

If condition (isUser == true && (ResultId == 1 || ResultId == 2 )) is met then I am saying Result = "Pass" else I am assigning value from r.Result.

In the same way I want to check another condition (isUser == True && (ResultId == 5)) then I want to say Result = "Absent"

Upvotes: 2

Views: 1014

Answers (2)

Jasper Kent
Jasper Kent

Reputation: 3676

As suggested in the comments, this is getting way too complex for the ternary operator. If you have C#8 then you can use it in combination with the expression form of switch. Something like:

Result = isUser ? ResultId switch
{
    1 => "Pass",
    2 => "Pass",
    5 => "Absent",
    _ => r.Result
}
: r.Result;

Upvotes: 3

Saadi Toumi Fouad
Saadi Toumi Fouad

Reputation: 2829

You mean like this

Result = isUser && (ResultId == 1 || ResultId == 2 ) ?
 "Pass" : isUser && ResultId == 5 ? "Absent" : r.result;

Upvotes: 0

Related Questions