如何使用Linq.Expressions查询集合 [英] How to query collection with Linq.Expressions
本文介绍了如何使用Linq.Expressions查询集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我建了一个自定义的IQueryable提供程序。提供者转换查询例如
I built a custom IQueryable provider. The provider transforms query for example
c.PurchaseDate == new DateTime(2011, 11, 29) && c.Name == "Elizabeth Brown"
从底层代码到System.Linq.Expressions.Expression
from underlying code into System.Linq.Expressions.Expression
现在我需要使用Linq查询对这个集合运行它们
Now I need to run them against this collection with Linq query
IQueryable<Customer> customers = _customers.AsQueryable();
任何人都可以告诉我如何使用Expression查询集合
Can anyone tell me how to query the collection with 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是真正奇怪的东西。享受!
I finished with the task this way. IQueryable is really wonderfull stuff. Enjoy!
这篇关于如何使用Linq.Expressions查询集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文