select all when variable is empty or null else select values filtered

2.5k views Asked by At

My linq query to summarize something like -

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

and query goes on to select values needed

here how to select all values (like select * >> without filter) when CustomerID value is ALL/NULL.? How to frame the where clause for this purpose?

I can rewrite same query with if else to have two different queries to handle this issue but is there any simpler way to do?

1

There are 1 answers

0
Giorgos Betsos On BEST ANSWER

Try this:

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) 

If CustomerID is empty or null or "ALL", then either the first or the second predicate in the where clause evaluate to true and no filtering is applied. If CustomerID is not empty AND not null AND not "ALL", then you end up with the initial query.