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!
Rather than building a lambda expression, build up the query bit by bit:
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
Wherecall – is rather harder, unfortunately.)