Reputation: 3129
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
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
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