linq - 如何使用 Linq.Expressions 查询集合

标签 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 查询集合?

谢谢

最佳答案

//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 真是太棒了。享受!

关于linq - 如何使用 Linq.Expressions 查询集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8876059/

相关文章:

c# - Lambda/LINQ 选择最小值

c# - 将使用 GROUP BY 和 COUNT 的查询转换为 Linq

sql-server-2008 - System.Net.WebException : The request failed with HTTP status 400: Bad Request. 动态调用 Web 服务

c# - 如何使用 EntityFramework Reverse POCO Generator 生成导航属性?

c# - Expression.Call groupBy 然后选择?

sql - 如何避免在 WHERE 查询中为 Unicode 字符串添加 'N' 前缀?

javascript - vb 中的 Javascript .map 等价物是什么?

asp.net - MVC 的最佳实践.. ViewModel 绑定(bind)使用接口(interface)示例

nhibernate - nHibernate 中的 'Bag' 和 'Set' 是什么?

c# - 在 C# 中将 HTTP Accept 和 Content-Type header 都设置为 "application/xml"