對於(&&,||),運算的對象是邏輯值,也就是True/False &&相當與中文的並且,||相當於中文的或者 。(叫做邏輯運算符又叫短路運算符) 運算結果只有下列四種情況。 True && True = True (左邊為true,再驗證右邊也為true,返回結果true)假如這是一個查詢條件,則執行。 True && False = False (左邊為true,再驗證右邊為false,返回結果false)假如這是一個查詢條件,不執行。 False && True = False (左邊為false,發生短路現象。右邊不再執行,直接返回false).........同樣不執行。 False && False = False (同上) True || True = True (左邊為true,發生短路現象,右邊不執行,直接返回true).......執行 True || False = True (左邊為true,發生短路現象,右邊不執行,直接返回true).......執行 False || True = True (左邊為false,再驗證右邊為true,返回結果true)............執行 False || False = False (左邊為false,再驗證右邊也為false,返回結果false).......不執行
對於(&,|),運算的對象是位,也就是1/0,叫做位運算符 理解:0為false,1為true(通用:0表示假,所有非零的數表示真。 ######方便記憶:0,什么都沒有騙人的,則為假) 運算結果只有下列四種情況。 1 & 1 = 1 1 & 0 = 0 0 & 1 = 0 0 & 0 = 0 1 | 1 = 1 1 | 0 = 1 0 | 1 = 1 0 | 0 = 0 &&和&對於他們各自的運算對象來說,結果是一樣的。
下面用一段代碼來說明||在實際代碼中的運用
var data = svc.DeclarationHeads.Include("TaxType").Where(f => f.CorporationCode == param.CorporationCode && f.FlowSign == 2 && (!param.TaxTypeId.HasValue || f.TaxTypeId == param.TaxTypeId)).ToList();
當傳入的參數中TaxTypeId==null時,param.TaxTypeId.HasValue為true,發生短路現象,右邊不執行,返回結果true。
則實際執行代碼:var data = svc.DeclarationHeads.Include("TaxType").Where(f => f.CorporationCode == param.CorporationCode && f.FlowSign == 2 ).ToList();
當傳入的參數中TaxTypeId==123時,param.TaxTypeId.HasValue為false,執行右邊的代碼,即f.TaxTypeId == 123,
則實際執行代碼:var data = svc.DeclarationHeads.Include("TaxType").Where(f => f.CorporationCode == param.CorporationCode && f.FlowSign == 2 && f.TaxTypeId == 123 ).ToList();
適用范圍:當我們再勾選條件進行查詢或者操縱數據庫時,可以任意選擇條件個數進行查詢,而只需調用同一個方法。(即一個服務完成多重條件的查詢)減少冗余代碼。