[英]How to place an If/Else statement in a where clause in a linq query?
如何在這個linq語句中放置if else?
where instruct.InstructorInstrNo == royalHIstory.RoyalIns.ToString()
我想做點什么
where instruct.InstructorInstrNo == if(royalHIstory.RoyalIns.ToString().Length == 3) "0" + royalHIstory.RoyalIns.ToString() else royalHIstory.RoyalIns.ToString()
我認為在使用lambda表達式時可以做類似的事情,但我的查詢不能並且不確定如何將我的查詢轉換為僅使用lambda表達式
它被稱為三元運算符或三元條件運算符(?:)
where instruct.InstructorInstrNo ==
(royalHIstory.RoyalIns.ToString().Length == 3
? "0" + royalHIstory.RoyalIns.ToString()
: royalHIstory.RoyalIns.ToString())
或者,使用PadLeft功能
where instruct.InstructorInstrNo == royalHIstory.RoyalIns.ToString().PadLeft(4, '0')
或者簡單地說(假設RoyalIns是一個整數類型)
where instruct.InstructorInstrNo == royalHIstory.RoyalIns.ToString("0000")
使用條件運算符 :
where instruct.InstructorInstrNo == ((royalHIstory.RoyalIns.ToString().Length == 3) ?
"0" + royalHIstory.RoyalIns.ToString() : royalHIstory.RoyalIns.ToString())
來自文檔:
條件運算符(?:)根據布爾表達式的值返回兩個值中的一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.