Lambda 表达式搜索
我想对具有可变搜索条件的产品执行相当于“动态 SQL”搜索,但使用 C# 代码。例如,产品的定义如下:
class Product
{
public decimal Price { get; set; }
public int Quantity { get; set; }
}
我的搜索控件有一个用于价格的文本框和一个用于数量的文本框。如果用户指定了某些内容,则应将其包含在搜索中(否则不包含在搜索中)。事实上,我的产品有两个以上的特性。
如何根据变量标准的任何此类搜索来构建通用的 lambda 表达式?
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要构建 lambda 表达式,而是一点一点地构建查询:
请注意,在您开始使用结果之前,这不会执行查询。
查询组合是 LINQ 的关键优势之一。 (不幸的是,表达式树组合 - 如果您想要单个
Where
调用,则需要执行此操作 - 相当困难。)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
Where
call - is rather harder, unfortunately.)