How to request a fee using Linq.Expressions

I built a custom IQueryable provider. The provider converts the request, for example

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

from the base code to System.Linq.Expressions.Expression

Now I need to run them against this collection using the Linq query

 IQueryable<Customer> customers = _customers.AsQueryable(); 

Can someone tell me how to request a collection using Expression?

thanks

+4
source share
1 answer
 //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(); 

I finished the task this way. IQueryable is really great stuff. Enjoy it!

+3
source

Source: https://habr.com/ru/post/1391193/


All Articles