Expression Trees
An expression tree is a representation of language-level code in the form of data. The data is stored in a
tree-like structure, hence the name.
Expression trees in LINQ are used for several reasons, one of which is to structure queries that utilize data
sources that implement IQueryable(Of T). At runtime, when a query is executed, the C# or Visual Basic
compiler translates the query expressions (and method-based queries) into code that is then converted
to an expression tree structure. The appropriate query provider then translates the structure into the
query language for the targeted data source.
As you learned in the previous section, the LINQ to SQL provider implements IQueryable(Of T) for
querying relational data stores.
The great thing about expression trees is that, as a developer, you don’t need to build one or even negotiate
through an expression tree. The traversal of an expression tree is done for you, unless you feel the
strong urge to create your own query provider or query language.
As a quick note, expression trees are also used to represent lambda expressions. When a lambda
expression is assigned to a variable, a field, or a parameter of type Expression(Of TDelegate), the
compiler generates an expression tree which represents the lambda expression. There are several
standard query operator methods that have parameters of type Expression(Of TDelegate). Thus, you
are able to pass lambda expressions when these methods are called. The compiler will then create an
expression tree.