Chris
Chris

Reputation: 3129

How to place an If/Else statement in a where clause in a linq query?

How would I place an if else in this linq statement?

where instruct.InstructorInstrNo == royalHIstory.RoyalIns.ToString()

I would like to do something like

where instruct.InstructorInstrNo == if(royalHIstory.RoyalIns.ToString().Length == 3) "0" + royalHIstory.RoyalIns.ToString() else royalHIstory.RoyalIns.ToString()

I think something similar can be done when using lambda expressions but my query doesn't and not sure how to convert my query to use nothing but lambda expressions

Upvotes: 2

Views: 73

Answers (2)

Patrick McDonald
Patrick McDonald

Reputation: 65421

It's called the ternary operator or ternary conditional operator (?:)

where instruct.InstructorInstrNo == 
    (royalHIstory.RoyalIns.ToString().Length == 3
    ? "0" + royalHIstory.RoyalIns.ToString()
    : royalHIstory.RoyalIns.ToString())

Alternatively, use the PadLeft function

where instruct.InstructorInstrNo == royalHIstory.RoyalIns.ToString().PadLeft(4, '0')

or simply (assuming RoyalIns is an integer type)

where instruct.InstructorInstrNo == royalHIstory.RoyalIns.ToString("0000")

Upvotes: 4

YuvShap
YuvShap

Reputation: 3835

Using conditional operator:

where instruct.InstructorInstrNo == ((royalHIstory.RoyalIns.ToString().Length == 3) ? 
                                   "0" + royalHIstory.RoyalIns.ToString() : royalHIstory.RoyalIns.ToString())

From the docs:

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.

Upvotes: 3

Related Questions