Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Build Linq Lambda Expression

Tags:

c#

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.

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"));

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);

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?

like image 462
Dave Avatar asked Feb 19 '10 15:02

Dave


People also ask

Can we use dynamic in lambda expression?

In 2010, the Dynamic Type was introduced and that gave us the ability to create dynamic lambda expressions.

What is Dynamic LINQ?

The Dynamic LINQ library exposes a set of extension methods on IQueryable corresponding to the standard LINQ methods at Queryable, and which accept strings in a special syntax instead of expression trees.

What is LINQ and lambda expressions?

The term 'Lambda expression' has derived its name from 'lambda' calculus which in turn is a mathematical notation applied for defining functions. Lambda expressions as a LINQ equation's executable part translate logic in a way at run time so it can pass on to the data source conveniently.


1 Answers

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.

like image 135
tvanfosson Avatar answered Oct 13 '22 04:10

tvanfosson