如何为IQueryable应用表达式树?

时间:2015-06-05 15:44:07

标签: c# entity-framework linq-to-sql expression-trees iqueryable

有没有办法将手动创建的表达式树从一个IQueryable应用到另一个?例如:

IQueryable<string> p = Enumerable.Empty<string>().AsQueryable();
p = p.Where(pp => pp[0] == 'A');
p = p.Skip(2).Take(4);
p = p.OrderBy(pp => pp.Length);

var vv = new[] {"Afss", "Acv", "Adfv", "Bcvx", "Ng"}.AsQueryable();

// Filtering of the vv collection with expression from p 
var filteredResult = vv.Filter(p.Expression);

或者我们必须单独应用WhereOrderBy表达式?

3 个答案:

答案 0 :(得分:3)

简单CreateQuery调用不起作用,因为提供程序使用传递表达式的数据源。

在执行表达式之前,您需要将Enumerable.Empty<string>()替换为包含数据的集合:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

public class Program
{
    public static void Main()
    {
        IQueryable<string> p = Enumerable.Empty<string>().AsQueryable();
        p = p.Where(pp => pp[0] == 'A');
        p = p.Skip(2).Take(4);
        p = p.OrderBy(pp => pp.Length);

        var vv = new[] {"Afss", "Acv", "Adfv", "Bcvx", "Ng"}.AsQueryable();

        // Filtering of the vv collection with expression from p 
        var expr = ExpressionTreeConstantReplacer.CopyAndReplace(p.Expression, typeof(EnumerableQuery<string>), vv);
        var filteredResult = vv.Provider.CreateQuery<string>(expr);

        Console.Write("Source: \t");
        foreach(var temp in vv)
            Console.Write("{0} ", temp);

        Console.WriteLine();

        Console.Write("Filtered: ");
        foreach(var temp in filteredResult)
            Console.WriteLine(temp);
    }

    class ExpressionTreeConstantReplacer<T> : ExpressionVisitor
    {
        Type originalType;
        T replacementConstant;

        internal ExpressionTreeConstantReplacer(Type originalType, T replacementConstant)
        {
            this.originalType = originalType;
            this.replacementConstant = replacementConstant;
        }

        protected override Expression VisitConstant(ConstantExpression c)
        {
            return c.Type == originalType ? Expression.Constant(replacementConstant) : c;
        }
    }

    class ExpressionTreeConstantReplacer
    {
        internal static Expression CopyAndReplace<T>(Expression expression, Type originalType, T replacementConstant)
        {
            var modifier = new ExpressionTreeConstantReplacer<T>(originalType, replacementConstant);
            return modifier.Visit(expression);
        }
    }
}

答案 1 :(得分:2)

您可以访问查询的提供者并使用CreateQuery基于表达式创建查询,您可以从其他查询中获取表达式以传递给它:

var filteredResult = vv.Provider.CreateQuery<string>(p.Expression);

答案 2 :(得分:0)

我有一个类似的情况,我不得不在WCF上发送过滤/排序表达式。我找不到一种方法来为过滤器和排序表达式使用单个实例。我最终使用InterLinq中的SerializableExpression。没有解决你的特定问题,但我希望它有所帮助。