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 重写相同的查询,以便有两个不同的查询来处理这个问题,但是有没有更简单的方法呢?

4

1 回答 1

6

试试这个:

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”,那么您将得到初始查询。

于 2014-12-17T06:41:08.607 回答