How to create a dynamic Linq Join extension method
Posted
by Royd Brayshay
on Stack Overflow
See other posts from Stack Overflow
or by Royd Brayshay
Published on 2008-12-23T15:12:34Z
Indexed on
2010/04/09
1:53 UTC
Read the original article
Hit count: 939
There was a library of dynamic Linq extensions methods released as a sample with VS2008. I'd like to extend it with a Join method. The code below fails with a parameter miss match exception at run time. Can anyone find the problem?
public static IQueryable Join(this IQueryable outer, IEnumerable inner,
string outerSelector, string innerSelector, string resultsSelector,
params object[] values)
{
if (inner == null)
throw new ArgumentNullException("inner");
if (outerSelector == null)
throw new ArgumentNullException("outerSelector");
if (innerSelector == null)
throw new ArgumentNullException("innerSelector");
if (resultsSelector == null)
throw new ArgumentNullException("resultsSelctor");
LambdaExpression outerSelectorLambda =
DynamicExpression.ParseLambda(outer.ElementType, null,
outerSelector, values);
LambdaExpression innerSelectorLambda =
DynamicExpression.ParseLambda(inner.AsQueryable().ElementType,
null, innerSelector, values);
ParameterExpression[] parameters = new ParameterExpression[] {
Expression.Parameter(outer.ElementType, "outer"),
Expression.Parameter(inner.AsQueryable().ElementType,
"inner") };
LambdaExpression resultsSelectorLambda =
DynamicExpression.ParseLambda(parameters, null,
resultsSelector, values);
return outer.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Join", new Type[] {
outer.ElementType,
inner.AsQueryable().ElementType,
outerSelectorLambda.Body.Type,
innerSelectorLambda.Body.Type,
resultsSelectorLambda.Body.Type },
outer.Expression, inner.AsQueryable().Expression,
Expression.Quote(outerSelectorLambda),
Expression.Quote(innerSelectorLambda),
Expression.Quote(resultsSelectorLambda)));
}
I've now fixed it myself, here's the answer. Please vote it up or add a better one.
© Stack Overflow or respective owner