首页 文章

当变量为空或null时选择all,否则选择已过滤的值

提问于
浏览
0

我的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
.......................)

并继续查询以选择所需的值

这里如何在 CustomerID 值为ALL / NULL时选择所有值(如select * >>而不使用过滤器) . 如何为此目的框架where子句?

我可以用if else重写相同的查询,以便有两个不同的查询来处理这个问题,但有没有更简单的方法呢?

1 回答

  • 4

    试试这个:

    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)
    

    如果 CustomerID 为空或null或"ALL",则 where 子句中的第一个或第二个谓词将评估为 true ,并且不应用任何过滤 . 如果 CustomerID 不为空且不为空且不是"ALL",那么您最终会得到初始查询 .

相关问题