• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Expressions.LambdaExpression类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Linq.Expressions.LambdaExpression的典型用法代码示例。如果您正苦于以下问题:C# LambdaExpression类的具体用法?C# LambdaExpression怎么用?C# LambdaExpression使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



LambdaExpression类属于System.Linq.Expressions命名空间,在下文中一共展示了LambdaExpression类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: UpdateLambda

 protected LambdaExpression UpdateLambda(LambdaExpression lambda, Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters)
 {
     if (body != lambda.Body || parameters != lambda.Parameters || delegateType != lambda.Type) {
         return Expression.Lambda(delegateType, body, parameters);
     }
     return lambda;
 }
开发者ID:kpfaulkner,项目名称:Linq-To-Search,代码行数:7,代码来源:ExpressionVisitor.cs


示例2: GetMemberName

        /// <summary>
        /// Gets the name of the member used in the <paramref name="expression"/>.
        /// </summary>
        /// <param name="expression">
        /// The <see cref="T:LambdaExpression"/> that calls the class member
        /// whose name should be returned.
        /// </param>
        /// <returns>
        /// The name of the member used in the <paramref name="expression"/>.
        /// </returns>   
        public virtual string GetMemberName(LambdaExpression expression) {
            if (null == expression) throw new ArgumentNullException("expression");

            var body = expression.Body;
            if (body != null) {

                var try1 = body as UnaryExpression;
                if (try1 != null) {

                    var try11 = try1.Operand as MemberExpression;
                    if (try11 != null) {
                        return GetMemberName(try11);
                    }

                    var try12 = try1.Operand as MethodCallExpression;
                    if (try12 != null) {
                        return GetMemberName(try12);
                    }
                }

                var try2 = body as MemberExpression;
                if (try2 != null) {
                    return GetMemberName(try2);
                }

                var try3 = body as MethodCallExpression;
                if (try3 != null) {
                    return GetMemberName(try3);
                }
            }

            throw new InvalidTargetMemberException(expression);
        }
开发者ID:kyourek,项目名称:Ensues.Reflection,代码行数:43,代码来源:MemberResolver.cs


示例3: BuildText

        // Terminology used in this file:
        //
        // - a "statement" is something like "x.Foo? AS Bar"
        // - "text" is a collection of statements, like "x.Foo? AS Bar, y.Baz as Qak"
        public static ReturnExpression BuildText(LambdaExpression expression, bool camelCaseProperties)
        {
            var body = expression.Body;

            if (body.NodeType == ExpressionType.Convert &&
                body is UnaryExpression)
            {
                body = ((UnaryExpression)expression.Body).Operand;
            }

            string text;
            switch (body.NodeType)
            {
                case ExpressionType.MemberInit:
                    var memberInitExpression = (MemberInitExpression) body;
                    text = BuildText(memberInitExpression, camelCaseProperties);
                    return new ReturnExpression {Text = text, ResultMode = CypherResultMode.Projection};
                case ExpressionType.New:
                    var newExpression = (NewExpression) body;
                    text = BuildText(newExpression,camelCaseProperties);
                    return new ReturnExpression {Text = text, ResultMode = CypherResultMode.Projection};
                case ExpressionType.Call:
                    var methodCallExpression = (MethodCallExpression) body;
                    text = BuildText(methodCallExpression);
                    return new ReturnExpression {Text = text, ResultMode = CypherResultMode.Set};
                case ExpressionType.MemberAccess:
                    var memberExpression = (MemberExpression) body;
                    text = BuildText(memberExpression, camelCaseProperties);
                    return new ReturnExpression { Text = text, ResultMode = CypherResultMode.Set };
                default:
                    throw new ArgumentException(WithExpressionShouldBeOneOfExceptionMessage, "expression");
            }
        }
开发者ID:GProulx,项目名称:Neo4jClient,代码行数:37,代码来源:CypherWithExpressionBuilder.cs


示例4: GetDeleteExpression

        public override Expression GetDeleteExpression(MappingEntity entity, Expression instance, LambdaExpression deleteCheck)
        {
            var tables = this.mapping.GetTables(entity);
            if (tables.Count < 2)
            {
                return base.GetDeleteExpression(entity, instance, deleteCheck);
            }

            var commands = new List<Expression>();
            foreach (var table in this.GetDependencyOrderedTables(entity).Reverse())
            {
                TableExpression tex = new TableExpression(new TableAlias(), entity, this.mapping.GetTableName(table));
                var where = this.GetIdentityCheck(tex, entity, instance);
                commands.Add(new DeleteCommand(tex, where));
            }

            Expression block = new BlockCommand(commands);

            if (deleteCheck != null)
            {
                var test = this.GetEntityStateTest(entity, instance, deleteCheck);
                return new IFCommand(test, block, null);
            }

            return block;
        }
开发者ID:rdrawsky,项目名称:iqtoolkit,代码行数:26,代码来源:AdvancedMapping.cs


示例5: IsValid

        public override bool IsValid(LambdaExpression expr)
        {
            // expression should be binary expresion
            if (!(expr.Body is BinaryExpression))
            {
                return false;
            }
            var body = expr.Body as BinaryExpression;

            //            // left operand should be binary expression
            //            if (!(body.Left is BinaryExpression))
            //            {
            //                return false;
            //            }
            //
            //            // right operand should be binary expression
            //            if (!(body.Right is BinaryExpression))
            //            {
            //                return false;
            //            }

            var lambdaParam = expr.Parameters[0];
            // check left operand
            if (!this.isExpressionValid(body.Left, lambdaParam))
            {
                return false;
            }

            // check right operand
            if (!this.isExpressionValid(body.Right, lambdaParam))
            {
                return false;
            }
            return true;
        }
开发者ID:chutinhha,项目名称:aiaintranet,代码行数:35,代码来源:CompositeExpressionBaseAnalyzer.cs


示例6: GetUpdateExpression

        public override Expression GetUpdateExpression(IMappedEntity entity, Expression instance, LambdaExpression updateCheck, LambdaExpression selector)
        {
            var IdentifiableAlias = new IdentifiableAlias();
            var table = new IdentifiableExpression(IdentifiableAlias, entity, ((OTypeMapping)this.Mapping).GetTableName(entity));

            var where = this.GetIdentityCheck(table, entity, instance);
            if (updateCheck != null)
            {
                Expression typeProjector = this.GetEntityExpression(table, entity);
                Expression pred = DbExpressionReplacer.Replace(updateCheck.Body, updateCheck.Parameters[0], typeProjector);
                where = where.And(pred);
            }

            var assignments = this.GetFieldAssignments(table, instance, entity, (e, m) => ((OTypeMapping)this.Mapping).IsUpdatable(e, m));

            Expression update = new UpdateCommandExpression(table, where, assignments);

            if (selector != null)
            {
                return CreateUpdateCommand(entity, instance, selector, where, assignments);
            }
            else
            {
                return update;
            }
        }
开发者ID:PaybackMan,项目名称:Cinder,代码行数:26,代码来源:OTypeMapper.cs


示例7: FindProperty

        public static PropertyInfo FindProperty(LambdaExpression lambdaExpression)
        {
            Expression expressionToCheck = lambdaExpression;

            bool done = false;

            while (!done)
            {
                switch (expressionToCheck.NodeType)
                {
                    case ExpressionType.Convert:
                        expressionToCheck = ((UnaryExpression) expressionToCheck).Operand;
                        break;
                    case ExpressionType.Lambda:
                        expressionToCheck = lambdaExpression.Body;
                        break;
                    case ExpressionType.MemberAccess:
                        var propertyInfo = ((MemberExpression) expressionToCheck).Member as PropertyInfo;
                        return propertyInfo;
                    default:
                        done = true;
                        break;
                }
            }

            return null;
        }
开发者ID:joaofx,项目名称:mvccontrib,代码行数:27,代码来源:ReflectionHelper.cs


示例8: ReplaceParameters

		public static Expression ReplaceParameters(LambdaExpression @in, IEnumerable<Expression> with)
		{
			Expression e = @in.Body;

			var withList = with.ToList();

			if (withList.Count() == @in.Parameters.Count)
			{
				e = @in.Parameters.Zip(withList, (parameter, replace) => new {parameter, replace})
					.Aggregate(e, (current, expression) => Rewrite(current, expression.parameter, expression.replace));
			}
			else
			{
				foreach (var parameter in @in.Parameters)
				{
					ParameterExpression parameter1 = parameter;
					foreach (var withParameter in withList.Where(withParameter => parameter1.Type == withParameter.Type))
					{
						e = Rewrite(e, parameter, withParameter);
						break;
					}
				}
			}

			return e;
		}
开发者ID:lakshithagit,项目名称:Target-Process-Plugins,代码行数:26,代码来源:LambdaSubstituter.cs


示例9: OutputFunctionBody

 private static string OutputFunctionBody(LambdaExpression function)
 {
     string body = function.Body.ToString();
     body = MemberPattern.Replace(body, string.Empty);
     body = BoxingPattern.Replace(body, "$1");
     return EscapeForTemplate(body);
 }
开发者ID:soxtoby,项目名称:EasyAssertions,代码行数:7,代码来源:FunctionFailureMessage.cs


示例10: ParsePattern

        private static Func<ExpressionIterationNode, bool> ParsePattern(LambdaExpression pattern)
        {
            //foreach (var node in pattern.Iterate())
            //{

            //}
        }
开发者ID:aaubry,项目名称:Fold,代码行数:7,代码来源:ExpressionMatchExtensions.cs


示例11: ExtractMemberName

 private static string ExtractMemberName(LambdaExpression expr)
 {
     var body = expr.Body;
     var parts = new List<string>();
     for(;;)
     {
         switch(body.NodeType)
         {
             case ExpressionType.Convert:
             case ExpressionType.ConvertChecked:
                 body = ((UnaryExpression)body).Operand;
                 break;
             case ExpressionType.MemberAccess:
                 var member = ((MemberExpression)body).Member;
                 if(!member.DeclaringType.IsDefined(typeof(CompilerGeneratedAttribute), true))
                     // Don't add access to compiler-generated classes to our path because an expression such as () => command.Member.SubMember will contain an access to the "command" member of an anonymous type.
                 {
                     parts.Add(member.Name);
                 }
                 body = ((MemberExpression)body).Expression;
                 break;
             case ExpressionType.Constant:
             case ExpressionType.Parameter:
                 goto breakOuter;
             default:
                 throw new ArgumentException("Expression must be a member expression, eg () => command.InvalidMember", "expr");
         }
     }
     breakOuter:
     return ((IEnumerable<string>)parts).Reverse().Join(".");
 }
开发者ID:RichieYang,项目名称:Composable.Monolithic,代码行数:31,代码来源:DomainCommandValidationException.cs


示例12: Match

        public static IEnumerable<Expression> Match(this LambdaExpression expression, LambdaExpression pattern)
        {
            //var patternSequence = pattern.Body.Iterate().ToList();
            //if (patternSequence.Count == 0)
            //{
            //    throw new ArgumentException("Invalid pattern", "pattern");
            //}

            //var rootNode = patternSequence[0];

            //var partialMatches = new List<PartialMatch>();

            //foreach (var node in expression.Iterate())
            //{
            //    partialMatches.Add(new PartialMatch { Root = node });

            //    for (var i = partialMatches.Count - 1; i >= 0; --i)
            //    {
            //        var partialMatch = partialMatches[i];
            //        if (Matches(node, patternSequence[partialMatch.Position]))
            //        {
            //            partialMatch.Position++;
            //            if (partialMatch.Position < patternSequence.Count)
            //            {
            //                continue;
            //            }
            //            yield return (Expression)partialMatch.Root.Element;
            //        }
            //        partialMatches.RemoveAt(i);
            //    }
            //}
        }
开发者ID:aaubry,项目名称:Fold,代码行数:32,代码来源:ExpressionMatchExtensions.cs


示例13: Inspect

 public void Inspect(LambdaExpression keysExpression, bool direction)
 {
     foreach (var columnMap in MapTransformer.Transform(keysExpression, queryBlock.QueryMap))
     {
         keyMap.Add(new ColumnMapAndDesc(columnMap, direction));
     }
 }
开发者ID:DzmitrySo,项目名称:sqLinq,代码行数:7,代码来源:OrderBlock.cs


示例14: Analyze

        internal static void Analyze(LambdaExpression e, PathBox pb)
        {
            bool knownEntityType = CommonUtil.IsClientType(e.Body.Type);
            pb.PushParamExpression(e.Parameters.Last());

            if (!knownEntityType)
            {
                NonEntityProjectionAnalyzer.Analyze(e.Body, pb);
            }
            else
            {
                switch (e.Body.NodeType)
                {
                    case ExpressionType.MemberInit:
                        EntityProjectionAnalyzer.Analyze((MemberInitExpression)e.Body, pb);
                        break;
                    case ExpressionType.New:
                        throw new NotSupportedException(SR.ALinqCannotConstructKnownEntityTypes);
                    case ExpressionType.Constant:
                        throw new NotSupportedException(SR.ALinqCannotCreateConstantEntity);
                    default:
                        NonEntityProjectionAnalyzer.Analyze(e.Body, pb);
                        break;
                }
            }

            pb.PopParamExpression();
        }
开发者ID:huoxudong125,项目名称:azure-sdk-for-net,代码行数:28,代码来源:ProjectionAnalyzer.cs


示例15: Combine

		public static LambdaExpression Combine(this LambdaExpression outer, LambdaExpression inner)
		{
			var invoke = Expression.Invoke(inner, outer.Body);
			var body = new ExpressionRewriter().AutoInline(invoke);

			return Expression.Lambda(body, outer.Parameters.ToArray());
		}
开发者ID:trullock,项目名称:MuonKit.Csv,代码行数:7,代码来源:ExpressionExtensions.cs


示例16: Optimize

        /**
         * приводит лямбду (x, y, ...) => ... к виду:  (x, y, ...) => fn(p, q, ...)
         *  где fn - оптимизированная лямбда, p, q - предварительно вычисленные выражения
         *
         *  пример:
         *  Func<int, int, Func<int, int, int, int>, int> fn = (int x, int y, Func<int, int, int, int> Foo) => Foo(F(x), F(y), F(2 * y));
         *  Func<int, int, int> optimizedLambda = (int x, int y) => fn(1, 2, (int p, int q, int l) => p > q ? p : (p < l ? l : q));
         */
        public Expression Optimize(LambdaExpression lambda, string functionName)
        {
            if (_methodCalls != null)
                _methodCalls.Clear();
            else
                _methodCalls = new Dictionary<string, MethodCall>();

            _innerLambdaParams = new List<Expression>();

            _functionName = functionName;

            //  получаем оптимизированную лямбду
            Expression fn = BuildInnerLambda(lambda);

            //  копируем параметры для новой лямбды
            ParameterExpression[] parameters = new ParameterExpression[lambda.Parameters.Count];
            lambda.Parameters.CopyTo(parameters, 0);

            //  собираем новую лямбду
            Expression optimizedLambda = Expression.Lambda(
                Expression.Invoke(fn, _innerLambdaParams),
                parameters
            );

            return optimizedLambda;
        }
开发者ID:CosmicPirate,项目名称:ExpressionOptimization,代码行数:34,代码来源:ExpressionOptimizer.cs


示例17: ExpressionsPrinter

        public ExpressionsPrinter(LambdaExpression expression)
        {
            Contract.Requires(expression != null, "expression should not be null.");

            _stringParameters = EvaluateParameters(expression.Parameters);
            _stringBody = EvaluateBody(expression.Body);
        }
开发者ID:SergeyTeplyakov,项目名称:VerificationFakes,代码行数:7,代码来源:ExpressionsPrinter.cs


示例18: Analyze

        /// <summary>
        /// Analyzes a lambda expression to check whether it can be satisfied with
        /// $select and client-side materialization.
        /// </summary>
        /// <param name="le">Lambda expression.</param>
        /// <param name="re">Resource expression in scope.</param>
        /// <param name="matchMembers">Whether member accesses are matched as top-level projections.</param>
        /// <returns>true if the lambda is a client-side projection; false otherwise.</returns>
        internal static bool Analyze(LambdaExpression le, ResourceExpression re, bool matchMembers)
        {
            Debug.Assert(le != null, "le != null");

            if (le.Body.NodeType == ExpressionType.Constant)
            {
                if (ClientType.CheckElementTypeIsEntity(le.Body.Type))
                {
                    throw new NotSupportedException(Strings.ALinq_CannotCreateConstantEntity);
                }

                re.Projection = new ProjectionQueryOptionExpression(le.Body.Type, le, new List<string>());
                return true;
            }

            if (le.Body.NodeType == ExpressionType.MemberInit || le.Body.NodeType == ExpressionType.New)
            {
                AnalyzeResourceExpression(le, re);
                return true;
            }

            if (matchMembers)
            {
                // Members can be projected standalone or type-casted.
                Expression withoutConverts = SkipConverts(le.Body);
                if (withoutConverts.NodeType == ExpressionType.MemberAccess)
                {
                    AnalyzeResourceExpression(le, re);
                    return true;
                }
            }

            return false;
        }
开发者ID:JianwenSun,项目名称:cc,代码行数:42,代码来源:ProjectionAnalyzer.cs


示例19: CompilePlan

        /// <summary>Creates a projection plan from the specified <paramref name="projection"/>.</summary>
        /// <param name="projection">Projection expression.</param>
        /// <param name="normalizerRewrites">Tracks rewrite-to-source rewrites introduced by expression normalizer.</param>
        /// <returns>A new <see cref="ProjectionPlan"/> instance.</returns>
        internal static ProjectionPlan CompilePlan(LambdaExpression projection, Dictionary<Expression, Expression> normalizerRewrites)
        {
            Debug.Assert(projection != null, "projection != null");
            Debug.Assert(projection.Parameters.Count == 1, "projection.Parameters.Count == 1");
            Debug.Assert(
                projection.Body.NodeType == ExpressionType.Constant ||
                projection.Body.NodeType == ExpressionType.MemberInit ||
                projection.Body.NodeType == ExpressionType.MemberAccess ||
                projection.Body.NodeType == ExpressionType.Convert ||
                projection.Body.NodeType == ExpressionType.ConvertChecked ||
                projection.Body.NodeType == ExpressionType.New,
                "projection.Body.NodeType == Constant, MemberInit, MemberAccess, Convert(Checked) New");

            ProjectionPlanCompiler rewriter = new ProjectionPlanCompiler(normalizerRewrites);
#if TRACE_CLIENT_PROJECTIONS
            Trace.WriteLine("Projection: " + projection);
#endif

            Expression plan = rewriter.Visit(projection);
#if TRACE_CLIENT_PROJECTIONS
            Trace.WriteLine("Becomes: " + plan);
#endif

            ProjectionPlan result = new ProjectionPlan();
            result.Plan = (Func<object, object, Type, object>)((LambdaExpression)plan).Compile();
            result.ProjectedType = projection.Body.Type;
#if DEBUG
            result.SourceProjection = projection;
            result.TargetProjection = plan;
#endif
            return result;
        }
开发者ID:JianwenSun,项目名称:cc,代码行数:36,代码来源:ProjectionPlanCompiler.cs


示例20: JoinExpressionNode

        public JoinExpressionNode(
        MethodCallExpressionParseInfo parseInfo,
        Expression innerSequence,
        LambdaExpression outerKeySelector,
        LambdaExpression innerKeySelector,
        LambdaExpression resultSelector)
            : base(parseInfo)
        {
            ArgumentUtility.CheckNotNull ("innerSequence", innerSequence);
              ArgumentUtility.CheckNotNull ("outerKeySelector", outerKeySelector);
              ArgumentUtility.CheckNotNull ("innerKeySelector", innerKeySelector);
              ArgumentUtility.CheckNotNull ("resultSelector", resultSelector);

              if (outerKeySelector.Parameters.Count != 1)
            throw new ArgumentException ("Outer key selector must have exactly one parameter.", "outerKeySelector");
              if (innerKeySelector.Parameters.Count != 1)
            throw new ArgumentException ("Inner key selector must have exactly one parameter.", "innerKeySelector");
              if (resultSelector.Parameters.Count != 2)
            throw new ArgumentException ("Result selector must have exactly two parameters.", "resultSelector");

              InnerSequence = innerSequence;
              OuterKeySelector = outerKeySelector;
              InnerKeySelector = innerKeySelector;
              ResultSelector = resultSelector;

              _cachedOuterKeySelector = new ResolvedExpressionCache<Expression> (this);
              _cachedInnerKeySelector = new ResolvedExpressionCache<Expression> (this);
              _cachedResultSelector = new ResolvedExpressionCache<Expression> (this);
        }
开发者ID:nicocrm,项目名称:DotNetSDataClient,代码行数:29,代码来源:JoinExpressionNode.cs



注:本文中的System.Linq.Expressions.LambdaExpression类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Expressions.ListInitExpression类代码示例发布时间:2022-05-26
下一篇:
C# Expressions.LabelTarget类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap