Пример #1
0
        /// <summary>
        /// Returns compiled lambda expression for given expression
        /// </summary>
        /// <typeparam name="T1">Input type on which to apply expression</typeparam>
        /// <typeparam name="T2">Return type for the expression</typeparam>
        /// <param name="exString">expression formula</param>
        /// <returns>Compiled lambda expression</returns>
        public static Func <T1, T2> CompileExpression <T1, T2>(ExpressionString exString)
        {
            var param = Expression.Parameter(typeof(T1));
            var expr  = BuildExpression <T1>(exString, param);

            return(Expression.Lambda <Func <T1, T2> >(expr, param).Compile());
        }
Пример #2
0
        /// <summary>
        /// Build and returns binary expression based on given expression formula
        /// </summary>
        /// <typeparam name="T">Type of expression to return</typeparam>
        /// <param name="exString">expression formula</param>
        /// <param name="param">Type used to identify operand in the expression</param>
        /// <returns>Returns binary expression based on given formula</returns>
        public static Expression BuildExpression <T>(ExpressionString exString, ParameterExpression param)
        {
            var            left         = MemberExpression.Property(param, exString.LeftSide);
            var            leftPropType = typeof(T).GetProperty(exString.LeftSide).PropertyType;
            ExpressionType exprBinary;

            if (ExpressionType.TryParse(exString.Operator, out exprBinary))
            {
                var right = Expression.Constant(Convert.ChangeType(exString.RightSide, leftPropType));
                return(Expression.MakeBinary(exprBinary, left, right));
            }
            else
            {
                throw new Exception("Invalid Expression");
            }
        }