What types and arguments does the method, "Any" when using Expression.Call take?
I have an inner and an outer Expression that I would like to use with Any. The expressions are built programatically.
Inner (this works):
ParameterExpression tankParameter = Expression.Parameter(typeof(Tank), "t");
Expression tankExpression = Expression.Equal(
Expression.Property(tankParameter, "Gun"),
Expression.Constant("Really Big"));
Expression<Func<Tank, bool>> tankFunction =
Expression.Lambda<Func<Tank, bool>>(tankExpression, tankParameter);
Outer (looks correct):
ParameterExpression vehicleParameter = Expression.Parameter(typeof(Vehicle), "v");
Expression vehicleExpression = Expression.Lambda(
Expression.Property(
vehicleParameter,
typeof(Vehicle).GetProperty("Tank")),
vehicleParameter);
This gives me 2 expressions:
v => v.Tank
t => t.Gun == "Really Big";
And I am looking for is:
v => v.Tank.Any(t => t.Gun == "Really Big");
I am attempting to use the Expression.Call method to use, "Any". 1. Is that the right way to do it? 2. The following throws an exception, "No method 'Any' on type 'System.Linq.Queryable' is compatible with the supplied arguments."
Here is how I am calling Any:
Expression any = Expression.Call(
typeof(Queryable),
"Any",
new Type[] { tankFunction.Body.Type }, // this should match the delegate...
tankFunction);
How is the Any called chained from vehicleExpression to tankFunction?
I had a similar problem when trying to get
string.Contains
to work; I just used theGetMethod
/MethodInfo
approach instead; however - it is complicated because it is a generic method...This should be the right
MethodInfo
- but it is hard to give a full (runnable) answer without a bit more clarity onTank
andVehicle
:Note that extension methods work backwards - so you actually want to call
method
with the two args (the source and the predicate).Something like:
If in doubt, use reflector (and fiddle it a bit ;-p) - for example, I wrote a test method as per your spec:
And decompiled it and toyed with it...