Invoke() static private method

Creates an InvocationExpression that applies a delegate or lambda expression with no arguments.
/// is null. /// .Type does not represent a delegate type or an . /// The number of arguments does not contain match the number of parameters for the delegate represented by .
static private Invoke ( Expression expression ) : InvocationExpression
expression Expression /// An that represents the delegate /// or lambda expression to be applied. ///
return InvocationExpression
示例#1
0
        /// <summary>
        /// Creates an expression that defines a logical AND function
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <returns></returns>
        public static Expression <Func <T, bool> > And <T>(this Expression <Func <T, bool> > left, Expression <Func <T, bool> > right)
        {
            var invokedExpr = XPR.Invoke(right, left.Parameters.Cast <XPR>());

            return(XPR.Lambda <Func <T, bool> >
                       (XPR.AndAlso(left.Body, invokedExpr), left.Parameters));
        }
示例#2
0
        static LambdaExpression EmptyWrapper(LambdaExpression functionLambda)
        {
            // We do the following transformation
            //     arg => arg
            // to
            //    arg => (arg => arg)(arg)
            //      public static string dnaParameterConvertTest(string optTest) {  ... };
            //
            // to
            //      (optTest) => dnaParameterConvertTest(optTest)
            ////      public static string dnaParameterConvertTest(string optTest)
            ////      {
            ////          return dnaParameterConvertTest(optTest);
            ////      };

            var newParams = functionLambda.Parameters.Select(p => Expression.Parameter(p.Type, p.Name)).ToList();

            var call = Expr.Invoke(functionLambda, newParams);

            return(Expr.Lambda(call, functionLambda.Name, newParams));


            //// build up the invoke expression for each parameter
            //var wrappingParameters = new List<ParameterExpression>(functionLambda.Parameters);
            //var paramExprs = functionLambda.Parameters.Select((param, i) =>
            //{
            //    // Starting point is just the parameter expression
            //    Expression wrappedExpr = param;
            //    return wrappedExpr;
            //}).ToArray();

            //var wrappingCall = Expr.Invoke(functionLambda, paramExprs);
            //return Expr.Lambda(wrappingCall, functionLambda.Name, wrappingParameters);
        }
示例#3
0
        /// <summary>
        /// Creates an expression tha defines an equality comparison
        /// </summary>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <returns></returns>
        public static Expression <Func <bool> > Equal <X>(this Expression <Func <X> > left, Expression <Func <X> > right)
        {
            var lValue = XPR.Invoke(left);
            var rValue = XPR.Invoke(right);

            return(XPR.Lambda <Func <bool> >(XPR.Equal(lValue, rValue)));
        }
示例#4
0
        public static Expression <Func <T, bool> > And <T>(this Expression <Func <T, bool> > expr1,
                                                           Expression <Func <T, bool> > expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast <Expression>());

            return(Expression.Lambda <Func <T, bool> >
                       (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters));
        }
示例#5
0
        static Expr InvokeExpression(DynamicMetaObject target, IEnumerable <Expr> mappedArgs, MethodInfo methodInfo)
        {
            var invokeExpr = Expr.Invoke(
                Expr.Convert(target.Expression, target.LimitType),
                mappedArgs);

            if (methodInfo.ReturnType == typeof(void))
            {
                return(Expr.Block(invokeExpr, Expr.Default(typeof(object))));
            }
            return(Expr.Convert(invokeExpr, typeof(object)));
        }
示例#6
0
        void ConvertArgumentToParamType(List <Argument> arguments, ParameterInfo[] parameters, out Expr failExpr)
        {
            failExpr = null;

            for (int i = 0; i < arguments.Count; i++)
            {
                var arg   = arguments[i];
                var param = parameters[i];

                if (param.ParameterType == typeof(bool) && arg.Type != typeof(bool))
                {
                    arg.Expression = ExprHelpers.ConvertToBoolean(context, arg.Expression);
                }
                else if (param.ParameterType == typeof(double) && arg.Type == typeof(string))
                {
                    arg.Expression = ExprHelpers.ConvertToNumberAndCheck(
                        context, arg.Expression,
                        ExceptionMessage.INVOKE_BAD_ARGUMENT_GOT, i + 1, "number", "string");
                }
                else if (param.ParameterType == typeof(string) && arg.Type != typeof(string))
                {
                    arg.Expression = Expr.Call(arg.Expression, MemberInfos.ObjectToString, arg.Expression);
                }
                else
                {
                    if (arg.Type == param.ParameterType || arg.Type.IsSubclassOf(param.ParameterType))
                    {
                        arg.Expression = Expr.Convert(arg.Expression, param.ParameterType);
                    }
                    else
                    {
                        Func <Expr, Expr> typeNameExpr =
                            obj => Expr.Invoke(
                                Expr.Constant((Func <object, string>)BaseLibrary.Type),
                                Expr.Convert(obj, typeof(object)));

                        // Ugly reflection hack
                        failExpr = Expr.Throw(
                            Expr.New(
                                MemberInfos.NewRuntimeException,
                                Expr.Constant(ExceptionMessage.INVOKE_BAD_ARGUMENT_GOT),
                                Expr.NewArrayInit(
                                    typeof(object),
                                    Expr.Constant(i + 1, typeof(object)),
                                    typeNameExpr(Expr.Constant(Activator.CreateInstance(param.ParameterType))),
                                    typeNameExpr(arg.Expression))));
                        break;
                    }
                }
            }
        }
示例#7
0
        public static IEnumerable<Book> GetResults(Expression<Func<Book, bool>> criteria)
        {
            IQueryable<Book> db = new[] {
                                            new Book { Title = "War and Peace", Author = "Leo Tolstoy"},
                                            new Book { Title = "Hunger", Author = "Knut Hamsun" },
                                            new Book { Title = "Embers", Author = "Sandor Marai" }
                                        }.AsQueryable();

            var query = from book in db.AsExpandable()
                        where criteria.Invoke(book)
                        select book;

            return query;
        }
示例#8
0
        public override Expression Compile(ParameterExpression stateParameterExpression, LabelTarget returnTarget)
        {
            switch (this.Op)
            {
            case "-":
                return
                    (Expr.Invoke(
                         (Expression <Func <object, object> >)
                             (x => x is float? - (float)x: LogicBuiltins.Negate(new List <object> {
                    x
                })),
                         Expr.Convert(this.Expression.Compile(stateParameterExpression, returnTarget), typeof(object))));

            default:
                throw new InvalidOperationException();
            }
        }
        private InvocationExpression InvocationExpression(
            ExpressionType nodeType, Type type, JObject obj)
        {
            var expression = Prop(obj, "expression", Expression);
            var arguments  = Prop(obj, "arguments", Enumerable(Expression));

            switch (nodeType)
            {
            case ExpressionType.Invoke:
                if (arguments == null)
                {
                    return(Expr.Invoke(expression));
                }
                return(Expr.Invoke(expression, arguments));

            default:
                throw new NotSupportedException();
            }
        }
        public LambdaExpression CreateLambda(Type from, Type to)
        {
            var input = Ex.Parameter(from, "input");
            var type  = Ex.Parameter(typeof(Type), "type");

            var block =
                Ex.Condition(
                    Ex.MakeBinary(Et.Equal, input, Ex.Default(typeof(object))),
                    NoResult(to),
                    Ex.Block(new[] { type },
                             Ex.Assign(type, Ex.Call(input, typeof(object).GetTypeInfo().GetDeclaredMethod(nameof(object.GetType)))),
                             Ex.Convert(Ex.Invoke(
                                            Ex.Call(Ex.Constant(Ref), nameof(IDataConverter.GetGeneralConverter), Type.EmptyTypes, type, Ex.Constant(to)),
                                            input),
                                        typeof(ConversionResult <>).MakeGenericType(to))));

            var lambda = Ex.Lambda(block, input);

            return(lambda);
        }
示例#11
0
        static ExpressionBase CreateInvokeExpression(string funcName, IReadOnlyCollection <ExpressionBase> args)
        {
            var lambda   = RegisterDelegates[funcName];
            var argTypes = lambda.GetType().GetMethod("Invoke").GetParameters();

            if (argTypes.Length == 0 || argTypes[0].GetCustomAttributes(typeof(ParamArrayAttribute), true).Length == 0)
            {
                if (lambda.Method.GetParameters().Length != args.Count)
                {
                    throw new InvalidOperationException($"函数{funcName}的参数数量不匹配。");
                }
            }
            else
            {
                args = new[] { ExpressionBase.NewArrayInit(typeof(object), args) };
            }
            var lambdaExpr = ExpressionBase.Constant(lambda);

            return(ExpressionBase.Invoke(lambdaExpr, args));
        }
示例#12
0
        public static Expression Invoke(Expression function, IDictionary <string, Expression> args)
        {
            if (ReferenceEquals(function, null))
            {
                throw new ArgumentNullException(nameof(function));
            }
            if (ReferenceEquals(args, null))
            {
                throw new ArgumentNullException(nameof(args));
            }
            var funcArgs = new LinqExpression [args.Count];
            var i        = 0;

            foreach (var param in ((LambdaExpression)function.internalExpression).Parameters)
            {
                funcArgs [i] = args [param.Name].internalExpression;
                i++;
            }
            return(new Expression(LinqExpression.Invoke(function, funcArgs)));
        }
示例#13
0
        public override Expression Compile(ParameterExpression stateParameterExpression, LabelTarget returnTarget)
        {
            Expression <Func <LogicStructureInstance, string, LogicField> > lookupField =
                (x, z) => x.Fields.Keys.First(y => y.Name == z);

            return
                (Expr.Property(
                     Expr.Property(
                         Expr.Convert(
                             this.Expression.Compile(stateParameterExpression, returnTarget),
                             typeof(LogicStructureInstance)),
                         "Fields"),
                     "Item",
                     Expr.Invoke(
                         lookupField,
                         Expr.Convert(
                             this.Expression.Compile(stateParameterExpression, returnTarget),
                             typeof(LogicStructureInstance)),
                         Expr.Constant(this.Field))));
        }
示例#14
0
        private Exp MakeStateRedirection(CompilerState state, Node node)
        {
            if (state == null)
            {
                throw new Exception();
            }
            if (node == null)
            {
                throw new Exception();
            }

            var data = node.Token.Data as Tokenizing.StateRedirectionData;

            if (data == null)
            {
                throw new Exception();
            }

            if (node.Children.Count < 1)
            {
                throw new Exception();
            }

            var functionargs = MakeRedirectionDescendants(state, node);
            var method       = FindCorrectRedirectionMethod(data.Type, functionargs);

            functionargs.Insert(0, state.FunctionState);
            functionargs.Insert(1, state.ErrorVariable);
            var callExp  = Exp.Call(null, method, functionargs);
            var oldState = state.FunctionState;

            state.FunctionState = Exp.Parameter(typeof(Character));
            var lambdaExp = Exp.Lambda(Make(state, node.Children[node.Children.Count - 1]), state.FunctionState);

            state.FunctionState = oldState;
            return(Exp.Invoke(lambdaExp, callExp));
        }
示例#15
0
 /// <summary>
 /// Creates an expression to call a function
 /// </summary>
 /// <param name="f">An expression representing the function to invoke</param>
 /// <param name="args"></param>
 /// <returns></returns>
 public static InvocationExpression invoke(XPR f, params XPR[] args)
 => XPR.Invoke(f, args);
示例#16
0
        static LambdaExpression ApplyMethodHandler(string functionName, LambdaExpression functionLambda, IFunctionExecutionHandler handler)
        {
            // public static int MyMethod(object arg0, int arg1) { ... }

            // becomes:

            // (the 'handler' object is captured and called mh)
            // public static int MyMethodWrapped(object arg0, int arg1)
            // {
            //    var fhArgs = new FunctionExecutionArgs("MyMethod", new object[] { arg0, arg1});
            //    int result = default(int);
            //    try
            //    {
            //        fh.OnEntry(fhArgs);
            //        if (fhArgs.FlowBehavior == FlowBehavior.Return)
            //        {
            //            result = (int)fhArgs.ReturnValue;
            //        }
            //        else
            //        {
            //             // Inner call
            //             result = MyMethod(arg0, arg1);
            //             fhArgs.ReturnValue = result;
            //             fh.OnSuccess(fhArgs);
            //             result = (int)fhArgs.ReturnValue;
            //        }
            //    }
            //    catch ( Exception ex )
            //    {
            //        fhArgs.Exception = ex;
            //        fh.OnException(fhArgs);
            //        // Makes no sense to me yet - I've removed this FlowBehavior enum value.
            //        // if (fhArgs.FlowBehavior == FlowBehavior.Continue)
            //        // {
            //        //     // Finally will run, but can't change return value
            //        //     // Should we assign result...?
            //        //     // So Default value will be returned....?????
            //        //     fhArgs.Exception = null;
            //        // }
            //        // else
            //        if (fhArgs.FlowBehavior == FlowBehavior.Return)
            //        {
            //            // Clear the Exception and return the ReturnValue instead
            //            // Finally will run, but can't further change return value
            //            fhArgs.Exception = null;
            //            result = (int)fhArgs.ReturnValue;
            //        }
            //        else if (fhArgs.FlowBehavior == FlowBehavior.ThrowException)
            //        {
            //            throw fhArgs.Exception;
            //        }
            //        else // if (fhArgs.FlowBehavior == FlowBehavior.Default || fhArgs.FlowBehavior == FlowBehavior.RethrowException)
            //        {
            //            throw;
            //        }
            //    }
            //    finally
            //    {
            //        fh.OnExit(fhArgs);
            //        // NOTE: fhArgs.ReturnValue is not used again here...!
            //    }
            //
            //    return result;
            //  }
            // }

            // CONSIDER: There are some helpers in .NET to capture the exception context, which would allow us to preserve the stack trace in a fresh throw.

            // Ensure the handler object is captured.
            var mh       = Expression.Constant(handler);
            var funcName = Expression.Constant(functionName);

            // Prepare the functionHandlerArgs that will be threaded through the handler,
            // and a bunch of expressions that access various properties on it.
            var fhArgs              = Expr.Variable(typeof(FunctionExecutionArgs), "fhArgs");
            var fhArgsReturnValue   = SymbolExtensions.GetProperty(fhArgs, (FunctionExecutionArgs mea) => mea.ReturnValue);
            var fhArgsException     = SymbolExtensions.GetProperty(fhArgs, (FunctionExecutionArgs mea) => mea.Exception);
            var fhArgsFlowBehaviour = SymbolExtensions.GetProperty(fhArgs, (FunctionExecutionArgs mea) => mea.FlowBehavior);

            // Set up expressions to call the various handler methods.
            // TODO: Later we can determine which of these are actually implemented, and only write out the code needed in the particular case.
            var onEntry     = Expr.Call(mh, SymbolExtensions.GetMethodInfo <IFunctionExecutionHandler>(meh => meh.OnEntry(null)), fhArgs);
            var onSuccess   = Expr.Call(mh, SymbolExtensions.GetMethodInfo <IFunctionExecutionHandler>(meh => meh.OnSuccess(null)), fhArgs);
            var onException = Expr.Call(mh, SymbolExtensions.GetMethodInfo <IFunctionExecutionHandler>(meh => meh.OnException(null)), fhArgs);
            var onExit      = Expr.Call(mh, SymbolExtensions.GetMethodInfo <IFunctionExecutionHandler>(meh => meh.OnExit(null)), fhArgs);

            // Create the new parameters for the wrapper
            var outerParams = functionLambda.Parameters.Select(p => Expr.Parameter(p.Type, p.Name)).ToArray();
            // Create the array of parameter values that will be put into the method handler args.
            var paramsArray = Expr.NewArrayInit(typeof(object), outerParams.Select(p => Expr.Convert(p, typeof(object))));

            // Prepare the result and ex(ception) local variables
            var result = Expr.Variable(functionLambda.ReturnType, "result");
            var ex     = Expression.Parameter(typeof(Exception), "ex");

            // A bunch of helper expressions:
            // : new FunctionExecutionArgs(new object[] { arg0, arg1 })
            var fhArgsConstr = typeof(FunctionExecutionArgs).GetConstructor(new[] { typeof(string), typeof(object[]) });
            var newfhArgs    = Expr.New(fhArgsConstr, funcName, paramsArray);
            // : result = (int)fhArgs.ReturnValue
            var resultFromReturnValue = Expr.Assign(result, Expr.Convert(fhArgsReturnValue, functionLambda.ReturnType));
            // : fhArgs.ReturnValue = (object)result
            var returnValueFromResult = Expr.Assign(fhArgsReturnValue, Expr.Convert(result, typeof(object)));
            // : result = function(arg0, arg1)
            var resultFromInnerCall = Expr.Assign(result, Expr.Invoke(functionLambda, outerParams));

            // Build the Lambda wrapper, with the original parameters
            var lambda = Expr.Lambda(
                Expr.Block(new[] { fhArgs, result },
                           Expr.Assign(fhArgs, newfhArgs),
                           Expr.Assign(result, Expr.Default(result.Type)),
                           Expr.TryCatchFinally(
                               Expr.Block(
                                   onEntry,
                                   Expr.IfThenElse(
                                       Expr.Equal(fhArgsFlowBehaviour, Expr.Constant(FlowBehavior.Return)),
                                       resultFromReturnValue,
                                       Expr.Block(
                                           resultFromInnerCall,
                                           returnValueFromResult,
                                           onSuccess,
                                           resultFromReturnValue))),
                               onExit, // finally
                               Expr.Catch(ex,
                                          Expr.Block(
                                              Expr.Assign(fhArgsException, ex),
                                              onException,
                                              Expr.IfThenElse(
                                                  Expr.Equal(fhArgsFlowBehaviour, Expr.Constant(FlowBehavior.Return)),
                                                  Expr.Block(
                                                      Expr.Assign(fhArgsException, Expr.Constant(null, typeof(Exception))),
                                                      resultFromReturnValue),
                                                  Expr.IfThenElse(
                                                      Expr.Equal(fhArgsFlowBehaviour, Expr.Constant(FlowBehavior.ThrowException)),
                                                      Expr.Throw(fhArgsException),
                                                      Expr.Rethrow()))))
                               ),
                           result),
                functionName,
                outerParams);

            return(lambda);
        }
示例#17
0
        /// <summary>
        /// Generate plots for the signal
        /// </summary>
        /// <param name="queryable"></param>
        /// <param name="sampleD"></param>
        /// <param name="mvaValue"></param>
        private static void PlotMVAResult(IQueryable<JetStream> source, FutureTDirectory dir, Expression<Func<TrainingTree, double>> mvaValue)
        {
            // Plot the weights. This can be used to plot signal vs background, ROC curves, etc.
            var weights = source
                .Select(j => TrainingUtils.TrainingTreeConverter.Invoke(j))
                .Select(j => Tuple.Create(mvaValue.Invoke(j), j.Weight))
                .FuturePlot(TrainingEventWeightFine.NameFormat, TrainingEventWeightFine.TitleFormat, TrainingEventWeightFine, "All")
                .Save(dir);

            // Next, let plot lots of kinematic plots so we can see what they look like.
            var plotsFromJS = new IPlotSpec<JetStream>[]
            {
                JetPtPlotJetStream,
                JetETPlotJetStream,
                JetEtaPlotJetStream,
                JetLxyPlotJetStream,
                JetCalRPlotJetStream,
                JetStreamSumPt,
                JetStreamMaxPt,
                JetCalRPlotFineJetStream,
            };

            var plots = plotsFromJS
                .Select(myp => myp.FromType<JetStream, Tuple<JetStream, double>>(jinfo => jinfo.Item1, weight: jinfo => jinfo.Item2 * jinfo.Item1.Weight));

            // We want weighted and unweighted plots here. We first have to normalize the weighting to be from 0 to 1.
            // If there is only a single weight in the sample (which is just weird) then correctly make sure we are set to deal
            // with things.
            var firstNonZeroBinValue = weights.Value.FindNonZeroBinValue();
            var lastNonZeroBinValue = weights.Value.FindNonZeroBinValue(HistogramUtils.BinSearchOrder.HighestBin);

            if (firstNonZeroBinValue == lastNonZeroBinValue)
            {
                Console.WriteLine($"  Sample has events with all one weight ({firstNonZeroBinValue}).");
            }

            var scaleing = lastNonZeroBinValue == firstNonZeroBinValue
                ? 1.0 
                : 1.0 / (lastNonZeroBinValue - firstNonZeroBinValue);

            firstNonZeroBinValue = lastNonZeroBinValue == firstNonZeroBinValue
                ? firstNonZeroBinValue - 1.0
                : firstNonZeroBinValue;

            var mvaWeithedJetStream = source
                .Select(j => Tuple.Create(j, j.Weight * (mvaValue.Invoke(TrainingUtils.TrainingTreeConverter.Invoke(j)) - firstNonZeroBinValue)*scaleing));
            var weithedJetStream = source
                .Select(j => Tuple.Create(j, j.Weight));

            // And run through each plot
            foreach (var p in plots)
            {
                mvaWeithedJetStream
                    .FuturePlot(p, "MVA")
                    .Save(dir);
                weithedJetStream
                    .FuturePlot(p, "")
                    .Save(dir);
            }
        }
示例#18
0
        /// <summary>
        /// Builds the childrens iterator.
        /// </summary>
        /// <param name="rootType">Type of the root.</param>
        /// <returns>
        /// A function that is able to process childrens from a node
        /// </returns>
        private static NodeProcessor BuildChildrensIterator(Type rootType)
        {
            var sourceParameter           = LinqExpression.Parameter(typeof(Node), "source");
            var explorerParameter         = LinqExpression.Parameter(typeof(NodeProcessorContext).MakeByRefType(), "nodeProcessorContext");
            var variableNodeProcessor     = LinqExpression.Variable(typeof(NodeProcessor), "nodeProcessor");
            var variableNodeListProcessor = LinqExpression.Variable(typeof(NodeListProcessor), "listProcessor");
            var statements = new List <LinqExpression>();

            // Cast source variable
            var castVar   = LinqExpression.Variable(rootType, "cast");
            var variables = new List <ParameterExpression> {
                castVar, variableNodeProcessor, variableNodeListProcessor
            };

            statements.Add(LinqExpression.Assign(castVar, LinqExpression.Convert(sourceParameter, rootType)));

            statements.Add(LinqExpression.Assign(variableNodeProcessor, LinqExpression.Field(explorerParameter, nodeProcessorProperty)));
            statements.Add(LinqExpression.Assign(variableNodeListProcessor, LinqExpression.Field(explorerParameter, nodeListProcessorProperty)));

            // Get all types from most inherited
            var types = new List <Type>();

            for (var type = rootType; type != null; type = type.GetTypeInfo().BaseType)
            {
                types.Add(type);
            }
            types.Reverse();

            // Iterate on inherited types
            foreach (var type in types)
            {
                // Iterate on all properties in order to create the iterator.
                foreach (var sourceField in type.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
                {
                    // If the property is not read-writable or contains a visitor ignore attribute, skip it
                    if (sourceField.GetCustomAttribute <VisitorIgnoreAttribute>(true) != null)
                    {
                        continue;
                    }

                    var propertyType = sourceField.FieldType;

                    var interfaces = propertyType.GetTypeInfo().ImplementedInterfaces;

                    // Get the property type and check if the property inherit from IList<>
                    if (!typeof(StatementList).GetTypeInfo().IsAssignableFrom(propertyType.GetTypeInfo()))
                    {
                        foreach (var interfaceBase in interfaces)
                        {
                            if (interfaceBase.GetTypeInfo().IsGenericType&& interfaceBase.GetTypeInfo().GetGenericTypeDefinition() == typeof(IList <>))
                            {
                                var parameterType = interfaceBase.GetTypeInfo().GenericTypeArguments[0];
                                if (typeof(Node).GetTypeInfo().IsAssignableFrom(parameterType.GetTypeInfo()))
                                {
                                    statements.Add(
                                        LinqExpression.Invoke(variableNodeListProcessor, LinqExpression.Field(castVar, sourceField), explorerParameter));
                                }
                                break;
                            }
                        }
                    }

                    if (typeof(Node).GetTypeInfo().IsAssignableFrom(propertyType.GetTypeInfo()))
                    {
                        statements.Add(
                            LinqExpression.Assign(
                                LinqExpression.Field(castVar, sourceField),
                                LinqExpression.Convert(LinqExpression.Invoke(variableNodeProcessor, LinqExpression.Field(castVar, sourceField), explorerParameter), propertyType)));
                    }
                }
            }

            // Return source parameter
            statements.Add(sourceParameter);

            // Lambda body
            var block = LinqExpression.Block(variables, statements);

            // Create lambda and return a compiled version
            var lambda = LinqExpression.Lambda <NodeProcessor>(block, sourceParameter, explorerParameter);

            return(lambda.Compile());
        }
示例#19
0
		/// <summary>
		/// Another way to formulate the preceding query.
		/// </summary>
		static void QueryCustomersManualJoin2 (Expression<Func<Purchase, bool>> purchasePredicate)
		{
			var data = new DemoData ();

			// Here we're including the purchasePredicate in the filteredPurchases expression. 
			// We can combine lambda expressions by calling Invoke() on the variable
			// expresssion.  The AsExpandable() wrapper then strips out the call to Invoke
			// and emits one clean expression:

			var query =
				from c in data.Customers.AsExpandable ()
				let filteredPurchases = data.Purchases.Where (
					p => p.CustomerID == c.ID && purchasePredicate.Invoke (p))
				where filteredPurchases.Any ()
				select new
				{
					c.Name,
					FilteredPurchases =
						from p in filteredPurchases
						select p.Price
				};

			foreach (var customerResult in query)
			{
				Console.WriteLine (customerResult.Name);
				foreach (decimal price in customerResult.FilteredPurchases)
					Console.WriteLine ("   $" + price);
			}
		}
 public override SysExpr ToExpression() => SysExpr.Invoke(Expression.ToExpression(), ArgumentsToExpressions());
示例#21
0
        // returnsConversion and the entries in paramsConversions may be null.
        static void ApplyConversions(ExcelFunctionRegistration reg, List <List <LambdaExpression> > paramsConversions, List <LambdaExpression> returnConversions)
        {
            // CAREFUL: The parameter transformations are applied in reverse order to how they're identified.
            // We do the following transformation
            //      public static string dnaParameterConvertTest(double? optTest) {   };
            //
            // with conversions convert1 and convert2 taking us from Type1 to double?
            //
            // to
            //      public static string dnaParameterConvertTest(Type1 optTest)
            //      {
            //          return convertRet2(convertRet1(
            //                      dnaParameterConvertTest(
            //                          paramConvert1(optTest)
            //                            )));
            //      };
            //
            // and then with a conversion from object to Type1, resulting in
            //
            //      public static string dnaParameterConvertTest(object optTest)
            //      {
            //          return convertRet2(convertRet1(
            //                      dnaParameterConvertTest(
            //                          paramConvert1(paramConvert2(optTest))
            //                            )));
            //      };

            Debug.Assert(reg.FunctionLambda.Parameters.Count == paramsConversions.Count);

            // NOTE: To cater for the Range COM type equivalance, we need to distinguish the FunctionLambda's parameter type and the paramConversion ReturnType.
            //       These need not be the same, but the should at least be equivalent.

            // build up the invoke expression for each parameter
            var wrappingParameters = reg.FunctionLambda.Parameters.Select(p => Expression.Parameter(p.Type, p.Name)).ToList();

            // Build the nested parameter convertion expression.
            // Start with the wrapping parameters as they are. Then replace with the nesting of conversions as needed.
            var paramExprs = new List <Expression>(wrappingParameters);

            for (int i = 0; i < paramsConversions.Count; i++)
            {
                var paramConversions = paramsConversions[i];
                if (paramConversions == null)
                {
                    continue;
                }

                // If we have a list, there should be at least one conversion in it.
                Debug.Assert(paramConversions.Count > 0);
                // Update the calling parameter type to be the outer one in the conversion chain.
                wrappingParameters[i] = Expr.Parameter(paramConversions.Last().Parameters[0].Type, wrappingParameters[i].Name);
                // Start with just the (now updated) outer param which will be the inner-most value in the conversion chain
                Expression wrappedExpr = wrappingParameters[i];
                // Need to go in reverse for the parameter wrapping
                // Need to now build from the inside out
                foreach (var conversion in Enumerable.Reverse(paramConversions))
                {
                    wrappedExpr = Expr.Invoke(conversion, wrappedExpr);
                }
                paramExprs[i] = wrappedExpr;
            }

            var wrappingCall = Expr.Invoke(reg.FunctionLambda, paramExprs);

            if (returnConversions != null)
            {
                foreach (var conversion in returnConversions)
                {
                    wrappingCall = Expr.Invoke(conversion, wrappingCall);
                }
            }

            reg.FunctionLambda = Expr.Lambda(wrappingCall, reg.FunctionLambda.Name, wrappingParameters);
        }
示例#22
0
 public void ClassSetUp() {
     calc = (i => i * 10);
     expr = LinqTool.Expr<int, int>(i => calc.Invoke(i) + 4);
     func = LinqTool.Func<int, int>(i => calc.Invoke(i) + 2);
 }
示例#23
0
        /// <summary>
        /// Do the cut
        /// </summary>
        /// <param name="effResults"></param>
        /// <param name="queryable1"></param>
        /// <param name="queryable2"></param>
        private static IFutureValue<double> CalcEff(FutureTDirectory effResults, Expression<Func<TrainingData,double>> selection, double threshold, IQueryable<TrainingData> background, IQueryable<TrainingData> signal)
        {
            background
                .Select(t => selection.Invoke(t))
                .FuturePlot("b_weight", "Background weight", 50, -1.1, 1.1)
                .Save(effResults);
            signal
                .Select(t => selection.Invoke(t))
                .FuturePlot("s_weight", "Signal weight", 50, -1.1, 1.1)
                .Save(effResults);

            var total_b = background.FutureCount();
            var total_s = signal.FutureCount();

            var selected_b = background.Where(t => selection.Invoke(t) > threshold).FutureCount();
            var selected_s = signal.Where(t => selection.Invoke(t) > threshold).FutureCount();

            var eff_b = from tb in total_b from ns in selected_b select (double) ns / (double) tb;
            var eff_s = from tb in total_s from ns in selected_s select (double) ns / (double) tb;

            //FutureWrite(from eb in eff_b from es in eff_s select $"Signal eff: {es}; Background eff: {eb}");

            return eff_s;
        }
示例#24
0
        public static Expression <Func <T, bool> > Or <T>(this Expression <Func <T, bool> > expr1, Expression <Func <T, bool> > expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters);

            return(Expression.Lambda <Func <T, bool> >(Expression.Or(expr1.Body, invokedExpr), expr1.Parameters));
        }