Passing in a lambda to a Where statement
- by sonicblis
I noticed today that if I do this:
var items = context.items.Where(i => i.Property < 2);
items = items.Where(i => i.Property > 4);
Once I access the items var, it executes only the first line as the data call and then does the second call in memory. However, if I do this:
var items = context.items.Where(i => i.Property < 2).Where(i => i.Property > 4);
I get only one expression executed against the context that includes both where statements. I have a host of variables that I want to use to build the expression for the linq lambda, but their presence or absence changes the expression such that I'd have to have a rediculous number of conditionals to satisfy all cases. I thought I could just add the Where() statements as in my first example above, but that doesn't end up in a single expression that contains all of the criteria. Therefore, I'm trying to create just the lambda itself as such:
//bogus syntax
if (var1 == "something")
var expression = Expression<Func<item, bool>>(i => i.Property == "Something);
if (var2 == "somethingElse")
expression = expression.Where(i => i.Property2 == "SomethingElse");
And then pass that in to the where of my context.Items to evaluate. A) is this right, and B) if so, how do you do it?