Search for a Lambda expression

I want to fulfill the equivalent of “dynamic SQL” search for a product with variable search criteria, but in C # code. For example, a product is defined as follows:

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

My search control has a text box for the price and a text box for the quantity. If the user indicates something, he should be included in the search (otherwise not). In fact, my product has many more than two properties.

How can I construct a lambda expression as a whole based on any such search using variable criteria?

Thanks!

+4
source share
1 answer

Instead of creating a lambda expression, create a query by bit:

 IQueryable<Product> productQuery = db.Products; if (userHasSpecifiedPrice) { productQuery = productQuery.Where(p => p.Price == userSpecifiedPrice) } // etc 

Please note that this will not execute the query until you start using the results.

Query composition is one of LINQ's key strengths. (Composing an expression tree is what you will need to do if you want a single Where call to be quite complicated, unfortunately.)

+8
source

Source: https://habr.com/ru/post/1345916/


All Articles