简体   繁体   English

使用ExpressionVisitor获取所有“where”调用

[英]Get all 'where' calls using ExpressionVisitor

I have a query, like such: 我有一个查询,像这样:

var query = from sessions in dataSet
                    where (names.Contains(sessions.Username))
                    where (sessions.Login.TimeOfAction == dt)                    
                    select new {    sessions.Username, 
                                    sessions.Login, 
                                    sessions.Logout, sessions.Duration };

I want to implement an ExpressionVisitor to extract BOTH the where clauses as Lambda's, but so far have only been able to get the first using a class called 'InnermostWhereFinder' that comes from the MSDN tutorial on a custom query provider for the TerraServer web-service. 我想实现一个ExpressionVisitor来提取where子句作为Lambda,但到目前为止只能使用一个名为'InnermostWhereFinder'的类来获得第一个,该类来自TerraServer Web服务的自定义查询提供程序上的MSDN教程。

It is: 它是:

internal class InnermostWhereFinder : ExpressionVisitor
    {
        private MethodCallExpression innermostWhereExpression;

        public MethodCallExpression GetInnermostWhere(Expression expression)
        {
            Visit(expression); 
            return innermostWhereExpression;
        }

        protected override Expression VisitMethodCall(MethodCallExpression expression)
        {
            if (expression.Method.Name == "Where")
                innermostWhereExpression = expression;

            Visit(expression.Arguments[0]);

            return expression;
        }
    }

Ive tried tweaking this class heavily to return both where clauses with no success. 我曾经尝试过大量调整这个类来返回两个没有成功的子句。 Couldn't find any great documentation on this, can anyone help? 找不到任何关于此的好文档,有人可以帮忙吗? This will ultimately need to result in multiple LambdaExpression objects I can work with, I think. 我认为这最终需要产生多个可以使用的LambdaExpression对象。

Use the class found here http://msdn.microsoft.com/en-us/library/bb882521%28v=vs.90%29.aspx as your base. 使用此处的课程http://msdn.microsoft.com/en-us/library/bb882521%28v=vs.90%29.aspx作为基础。 You can then create your Visitor like this 然后,您可以像这样创建您的访客

internal class WhereFinder : ExpressionVisitor
    {
        private IList<MethodCallExpression> whereExpressions = new List<MethodCallExpression>();

        public IList<MethodCallExpression> GetWhere(Expression expression)
        {
            Visit(expression); 
            return whereExpressions;
        }

        protected override Expression VisitMethodCall(MethodCallExpression expression)
        {
            if (expression.Method.Name == "Where")
                whereExpressions.Add(expression);

            Visit(expression.Arguments[0]);

            return expression;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM