动态构建 Linq Lambda 表达式 [英] Dynamically Build Linq Lambda Expression

查看:36
本文介绍了动态构建 Linq Lambda 表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我猜这已经在某处得到了回答,我只是对语法不够熟悉还没有理解,所以请耐心等待.

Okay, my guess is this is answered somewhere already, and I'm just not quite familiar enough with the syntax yet to understand, so bear with me.

我的 web 应用程序的用户需要过滤 gridview 中的一长串项目,通过 linqdatasource 访问.我正在使用 OnSelecting 事件来进一步过滤项目.我想根据用户在 DropDownLists 中所做的选择来过滤这些项目.

The users of my web app need to filter a long list of items in a gridview, accessed via a linqdatasource. I am using the OnSelecting Event to further filter items. I want to filter those items based on selections the users make in DropDownLists.

例如,他们选择标题"包含"弗雷德"这导致

For example, they select "Title" "Contains" "Fred" This results in

e.Result = dbContext.Opps.Where(opp => opp.Title.Contains("Fred"));

或描述"不包含"Alpha"结果

Or "Description" "Does not Contain" "Alpha" results in

 e.Result = dbContext.Opps.Where(opp => !opp.Description.Contains("Alpha"));

我想动态地构建该表达式 (System.Linq.Expressions.Expression>),而不是使用嵌套的 switch 表达式来生成它,因为我想检查许多字段,而且我还想使用 StartsWith 和 EndsWith 检查.如果我可以将表达式构建为字符串,如下所示:

I would like to build up that Expression (System.Linq.Expressions.Expression>) dynamically, instead of having nested switch expressions to generate it, as there are a number of fields I want to check, and I also want to use the StartsWith and EndsWith checks. If I could build the Expression as a string, like so:

string stringExpression = string.Format("opp => opp.{0}.{1}("{2}")",
    ddlCustomFilter.SelectedValue,
    ddlFilterType.SelectedValue,
    txtFilterText.Text);

然后以某种方式将其转换为表达式...这可能吗?或者我应该硬着头皮生成创建各种表达式所需的所有 switch() 语句?

And then somehow have it be converted into an Expression... is this possible? Or should I just bite the bullet and generate all the switch() statements required to create the various expressions?

推荐答案

您当然可以动态构建表达式,但我会考虑使用 Dynamic LINQ 首先作为替代方案,尽管您可能无法使用包含.此外,您可能需要考虑使用 PredicateBuilder 以附加方式构建复杂查询.

You could certainly build the expression dynamically, but I would consider using Dynamic LINQ as an alternative first, though you may not be able to use Contains. In addition, you may want to consider using PredicateBuilder to build complex queries additively.

这篇关于动态构建 Linq Lambda 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆