动态生成的Linq Lambda表达式 [英] Dynamically Build Linq Lambda Expression

查看:122
本文介绍了动态生成的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"));

或说明不包含,阿尔法
结果

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

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



我想建立该表达式(System.Linq.Expressions.Expression>)动态,而不是具有嵌套的开关表达式生成它,因为有一些我想检查领域,同时我也想使用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);



然后莫名其妙地就被转化成一个Expression ...这可能吗?或者我应该只是咬紧牙关,生成所有的开关()来创建各种表情所需的报表?

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?

推荐答案

您当然可以动态生成的表情,但我会考虑使用的动态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天全站免登陆