Mike Howe
Mike Howe

Reputation: 263

Using a condition in LINQ

How can I rewrite this using a condition in LINQ?

If the selectID = zero, I want this to run :

   var products = from p in product.Table
       orderby p.Name
       where (p.stock == stockId)
      select p;        

If the selectID NOT zero, I want this to run :

   var products = from p in product.Table
       orderby p.Name
       where (p.stock == stockId) &&        
             (p.Id == selectID)
      select p;             

This below works, but I have to use a "dummy" second condition (p.hidden == false) for the ternary operator to work :

   var products = from p in product.Table
       orderby p.Name
       where (p.stock == stockId) &&        
      (selectID != 0 ? p.Id == selectID : p.hidden == false)
      select p;             

Is there a way to get rid of (p.hidden == false) because it is not required in the logic and is just there to get the operator to work. thanks

Upvotes: 1

Views: 167

Answers (2)

ryanulit
ryanulit

Reputation: 5001

You could also write it like this:

var products = from p in product.Table
       orderby p.Name
       where (p.stock == stockId) &&        
             (p.Id == selectID || selectID == 0)
      select p;

The || selectID == 0 just returns true if the ID isn't supplied and still allows the query to run as you intended. The link below was how I learned this simple trick.

http://www.sommarskog.se/dyn-search-2008.html

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460158

You could use the same Id as the record as fallback value:

var products = from p in product.Table
               orderby p.Name
               where p.stock == stockId && 
                     p.Id == (selectID == 0 ? p.Id : selectID)
               select p; 

However, since that could lead to a less efficient query plan i would simply use an if-else:

var products = product.Table.Where(p => p.stock == stockId);
if(selectID != 0)
    products = products.Where(p => p.Id == selectID);
products = products.OrderBy(p=> p.Name);

Upvotes: 6

Related Questions