Mur*_*ala 0 c# sql linq linq-query-syntax
我的 linq 查询总结如下 -
string CustomerID;// can be "ALL" or any value
var itemlist = ( from itmhstry in context.ItemHistories
join itm in context.Items on itmhstry.ItemID equals itm.ItemID into itm_join
where itmhstry.CustomerID == CustomerID
.......................)
Run Code Online (Sandbox Code Playgroud)
然后查询继续选择所需的值
这里如何在CustomerID值为 ALL/NULL时选择所有值(如 select * >> without filter) 。?如何为此目的构建 where 子句?
我可以用 if else 重写相同的查询,以便有两个不同的查询来处理这个问题,但有没有更简单的方法呢?
尝试这个:
var itemlist = from itmhstry in context.ItemHistories
join itm in context.Items on itmhstry.ItemID equals itm.ItemID into itm_join
where string.IsNullOrEmpty(CustomerID) ||
(CustomerID == "ALL") ||
(itmhstry.CustomerID == CustomerID)
Run Code Online (Sandbox Code Playgroud)
如果CustomerID为空或 null 或“ALL”,则where子句中的第一个或第二个谓词评估为,true并且不应用过滤。如果CustomerID不为空且不为空且不为“ALL”,则您最终会得到初始查询。