有一个动态
LINQ扩展方法的库作为样例与
VisualStudio2008发布.我想用一个连接方法来扩展它.以下代码在运行时失败,参数缺失匹配异常.哪里有问题?
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,innerSelector,values); ParameterExpression[] parameters = new ParameterExpression[] { Expression.Parameter(outer.ElementType,"outer"),Expression.Parameter(inner.AsQueryable().ElementType,"inner") }; LambdaExpression resultsSelectorLambda = DynamicExpression.ParseLambda(parameters,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)) ); }
解决方法
我现在已经修好了将CreateQuery(…)调用的参数传给过多的一个小学生错误.将以下代码粘贴到DynamicQueryable类中的Dynamic.cs文件中,以进行动态连接扩展方法.您可以在
http://code.msdn.microsoft.com/csharpsamples找到DynamicQuery示例项目的源代码.
请享用.
请享用.
public static IQueryable Join(this IQueryable outer,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,values); LambdaExpression innerSelectorLambda = DynamicExpression.ParseLambda(inner.AsQueryable().ElementType,values); ParameterExpression[] parameters = new ParameterExpression[] { Expression.Parameter(outer.ElementType,"inner") }; LambdaExpression resultsSelectorLambda = DynamicExpression.ParseLambda(parameters,values); return outer.Provider.CreateQuery( Expression.Call( typeof(Queryable),new Type[] {outer.ElementType,resultsSelectorLambda.Body.Type },Expression.Quote(resultsSelectorLambda))); } //The generic overload. public static IQueryable<T> Join<T>(this IQueryable<T> outer,IEnumerable<T> inner,params object[] values) { return (IQueryable<T>)Join((IQueryable)outer,(IEnumerable)inner,values); }