老外写的一个不错的扩展表达式的文章,原文地址:http://www.albahari.com/nutshell/predicatebuilder.html

Dynamically Composing Expression Predicates

Suppose you wanted to write a LINQ to SQL query that implemented a keyword-style. search. In other words, a query that returned rows whose description contained some or all of a given set of keywords.

We could proceed as follows:

[转]Dynamically Composing Expression PredicatesIQueryable<Product> SearchProducts (params string[] keywords)
}

The temporary variable in the loop is required to avoid the outer variable trap, where the same variable is captured for each iteration of the foreach loop.

So far, so good. But this only handles the case where you want to match all of the specified keywords. Suppose instead, we wanted products whose description contains any of the supplied keywords. Our previous approach of chaining Where operators is completely useless! We could instead chain Union operators, but this would be inefficient. The ideal approach is to dynamically construct a lambda expression tree that performs an or-based predicate.

Of all the things that will drive you to manually constructing expression trees, the need for dynamic predicates is the most common in a typical business application. Fortunately, it’s possible to write a set of simple and reusable extension methods that radically simplify this task. This is the role of our PredicateBuilder class.

Using PredicateBuilder

Here's how to solve the preceding example with PredicateBuilder:

 
[转]Dynamically Composing Expression PredicatesIQueryable<Product> SearchProducts (params string[] keywords)
}

PredicateBuilder Source Code

Here's the complete source:

[转]Dynamically Composing Expression Predicatesusing System;
[转]Dynamically Composing Expression Predicates
using System.Linq;
[转]Dynamically Composing Expression Predicates
using System.Linq.Expressions;
[转]Dynamically Composing Expression Predicates
using System.Collections.Generic;
[转]Dynamically Composing Expression Predicates 
[转]Dynamically Composing Expression Predicates
public static class PredicateBuilder
}

 

PredicateBuilder is also shipped as part of LINQKit, a productivity kit for LINQ to SQL.

How it Works

The True and False methods do nothing special: they are simply convenient shortcuts for creating an Expression<Func<T,bool>> that initially evaluates to true or false. So the following:

[转]Dynamically Composing Expression Predicatesvar predicate = PredicateBuilder.True <Product> ();

is just a shortcut for this:

[转]Dynamically Composing Expression PredicatesExpression<Func<Product, bool>> predicate = c => true;

When you’re building a predicate by repeatedly stacking and/or conditions, it’s useful to have a starting point of either true or false (respectively). Our SearchProducts method still works if no keywords are supplied.

The interesting work takes place inside the And and Or methods. We start by invoking the second expression with the first expression’s parameters. An Invoke expression calls another lambda expression using the given expressions as arguments. We can create the conditional expression from the body of the first expression and the invoked version of the second. The final step is to wrap this in a new lambda expression.

More Examples

A useful pattern in writing a data access layer is to create a reusable predicate library. Your queries, then, consist largely of select and orderby clauses, the filtering logic farmed out to your library. Here's a simple example:

[转]Dynamically Composing Expression Predicatespublic partial class Product
}

We can extend this by adding a method that uses PredicateBuilder:

[转]Dynamically Composing Expression Predicatespublic partial class Product
}

This offers an excellent balance of simplicity and reusability, as well as separating business logic from expression plumbing logic. To retrieve all products whose description contains “BlackBerry” or “iPhone”, along with the Nokias and Ericssons that are selling, you would do this:

[转]Dynamically Composing Expression Predicatesvar newKids  = Product.ContainsInDescription ("BlackBerry""iPhone");
[转]Dynamically Composing Expression Predicates
[转]Dynamically Composing Expression Predicatesvar classics 
= Product.ContainsInDescription ("Nokia""Ericsson")
[转]Dynamically Composing Expression Predicates                      .And (Product.IsSelling());
[转]Dynamically Composing Expression Predicatesvar query 
=
[转]Dynamically Composing Expression Predicates  from p 
in Data.Products.Where (newKids.Or (classics))
[转]Dynamically Composing Expression Predicates  select p;

The And and Or methods in boldface resolve to extension methods in PredicateBuilder.
An expression predicate can perform. the equivalent of an SQL subquery by referencing association properties. So, if Product had a child EntitySet called Purchases, we could refine our IsSelling method to return only those products that have sold a minimum number of units as follows:

[转]Dynamically Composing Expression Predicatespublic static Expression<Func<Product, bool>> IsSelling (int minPurchases)
}

 

相关文章:

  • 2022-12-23
  • 2022-02-12
  • 2021-10-31
  • 2021-09-21
  • 2022-12-23
  • 2022-12-23
  • 2021-05-22
  • 2021-10-27
猜你喜欢
  • 2021-09-21
  • 2022-03-01
  • 2022-12-23
  • 2021-10-16
  • 2021-05-29
  • 2021-11-29
  • 2021-12-17
相关资源
相似解决方案