我构建了一个自定义 IQueryable 提供程序。例如,提供者转换查询
c.PurchaseDate == new DateTime(2011, 11, 29) && c.Name == "Elizabeth Brown"
从底层代码到 System.Linq.Expressions.Expression
现在我需要使用 Linq 查询针对此集合运行它们
IQueryable<Customer> customers = _customers.AsQueryable();
谁能告诉我如何使用表达式查询集合?
Thanks
//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 确实是很棒的东西。享受!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)