I was looking up an example how to use a particular part of the Telerik grid framework (ASP.NET MVC3, but that’s not really relevant here). They have a chunk of code which takes a list of filter descriptions and builds an expression:
System.Linq.Expressions.Expression<Func<MyModel, bool> exp =
ExpressionBuilder.Expression<MyModel>(listOfFilters);
Ok, so I think that’s fine. The Expression wraps a lambda, which operates on MyModel to produce a bool. Great. Now, their example simply drops that into a Where like so:
someList = someList.Where(exp);
Which I am presuming should be “hey apply that expression to all the items in the list (which is of course generic MyModel too). However, VS claims that code doesn’t compile. I get “No overload Where exists or System.Func has some invalid arguments”.
I played around with it and find that I can compile the expression, which gives the more unseemly looking
someList = someList.Where(x => exp.Compile()(x));
Which does compile and would probably work, but it makes me uncomfortable because I’m now clearly operating outside what I know.
Is there some reason why (IDE setting, flag, stale documentation) the example’s approach doesn’t work?
Is there a rough equivalency to my hack and the example?
Should I structure that hack differently to avoid some hideous problem (like, its not going to compile the expression each and every time it checks an item in the list, right? I think it’s smart enough for that?)
— Edit
Yes it was IEnumerable. I fell into the “all Wheres are created equal” trap.
Thanks all!
Have you tried just doing
If someList is an
IEnumerableyou will need to useexp.Compile()which returns aFunc<MyModel,bool>If someList is an
IQueryableyou can useexp.Compile()or you can useexpwhich is anExpression<Func<MyModel, bool>>