Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Expression Search

I want to perform the equivalent of a 'dynamic SQL' search for a product with variable search criteria, but in C# code. For example, a product is defined like this:

class Product
{
  public decimal Price { get; set; }
  public int Quantity { get; set; }
}

My search control has a textbox for price and a textbox for quantity. If the user specifies something, it should be included in the search (otherwise not). In reality, my product has many more than 2 properties.

How can I build a lambda expression generically based on any such search by variable criteria?

Thanks!

like image 486
John Avatar asked Feb 25 '23 16:02

John


1 Answers

Rather than building a lambda expression, build up the query bit by bit:

IQueryable<Product> productQuery = db.Products;

if (userHasSpecifiedPrice)
{
    productQuery = productQuery.Where(p => p.Price == userSpecifiedPrice)
}
// etc

Note that this won't execute the query until you start to use the results.

Query composition is one of the key strengths of LINQ. (Expression tree composition - which is what you'd need to do if you wanted a single Where call - is rather harder, unfortunately.)

like image 183
Jon Skeet Avatar answered Feb 27 '23 05:02

Jon Skeet