当变量为空或 null 时选择全部,否则选择筛选的值

本文关键字:选择 筛选 全部 null 变量 | 更新日期: 2023-09-27 18:34:23

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

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

在这里,当值为 ALL/NULL 时,如何选择所有值(例如选择>>不带过滤器CustomerID * )。如何为此目的构建 where 子句?

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

当变量为空或 null 时选择全部,否则选择筛选的值

试试这个:

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不为空,不为空,也不是"全部",则最终会得到初始查询。