如何使用Linq.Expressions查询集合

时间:2012-01-16 05:21:28

标签: linq c#-4.0

我构建了一个自定义IQueryable提供程序。提供者转换查询例如

c.PurchaseDate == new DateTime(2011, 11, 29) && c.Name == "Elizabeth Brown"

从底层代码到System.Linq.Expressions.Expression

现在我需要使用Linq查询

对这个集合运行它们
IQueryable<Customer> customers = _customers.AsQueryable();

有人能告诉我如何使用Expression查询集合吗?

由于

1 个答案:

答案 0 :(得分:3)

//Query = c.PurchaseDate == new DateTime(2011, 11, 29) && c.Name
    // == "Elizabeth Brown" )
IQueryable<Customer> customers = _customers.AsQueryable<Customer>();

//Predicate parameter
ParameterExpression parameter = Expression.Parameter(typeof(Customer), 
                                                          "customer");

//Create left expression
Expression left = Expression.Property(parameter, typeof(Customer)
                                     .GetProperty("PurchaseDate"));
Expression right = Expression.Constant(new DateTime(2011, 11, 29));
Expression leftExp = Expression.Equal(left, right);

//Create right expression tree
left = Expression.Property(parameter, typeof(Customer).GetProperty("Name"));
right = Expression.Constant("Elizabeth Brown", typeof(string));
Expression rightExp = Expression.Equal(left, right);

//Combine the expressions into expression tree
Expression expressionTree = Expression.AndAlso(leftExp, rightExp);

//Create an expression tree that represents the expression
MethodCallExpression methodCall = Expression.Call(
    typeof(Queryable),
    "Where",
    new Type[] { customers.ElementType },
    customers.Expression,
    Expression
               .Lambda<Func<Customer, bool>>
                 (expressionTree, new ParameterExpression[] { parameter }));

// Create an executable query from the expression tree.
IQueryable<Customer> results = 
                customers.Provider.CreateQuery<Customer>(methodCall);

// Enumerate the results
foreach (Customer customer in results)
{
    Console.WriteLine("{0} {1}", customer.Name, customer.PurchaseDate);
}

Console.ReadLine();

我用这种方式完成了任务。 IQueryable真的很棒。享受!