Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><a href="http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx" rel="noreferrer">Lambda expressions</a> are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true; lambda expressions can be converted to expression trees which allows for a lot of the magic like LINQ to SQL. </p> <p>The following is an example of a <a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx" rel="noreferrer">LINQ to Objects</a> expression using anonymous delegates then lambda expressions to show how much easier on the eye they are:</p> <pre><code>// anonymous delegate var evens = Enumerable .Range(1, 100) .Where(delegate(int x) { return (x % 2) == 0; }) .ToList(); // lambda expression var evens = Enumerable .Range(1, 100) .Where(x =&gt; (x % 2) == 0) .ToList(); </code></pre> <p>Lambda expressions and anonymous delegates have an advantage over writing a separate function: they implement <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)" rel="noreferrer">closures</a> which can allow you to <a href="http://www.srtsolutions.com/Looking-Inside-C-Closures" rel="noreferrer">pass local state to the function without adding parameters</a> to the function or creating one-time-use objects.</p> <p><a href="http://www.interact-sw.co.uk/iangblog/2005/09/30/expressiontrees" rel="noreferrer">Expression trees</a> are a very powerful new feature of C# 3.0 that allow an API to look at the structure of an expression instead of just getting a reference to a method that can be executed. An API just has to make a delegate parameter into an <code>Expression&lt;T&gt;</code> parameter and the compiler will generate an expression tree from a lambda instead of an anonymous delegate:</p> <pre><code>void Example(Predicate&lt;int&gt; aDelegate); </code></pre> <p>called like:</p> <pre><code>Example(x =&gt; x &gt; 5); </code></pre> <p>becomes:</p> <pre><code>void Example(Expression&lt;Predicate&lt;int&gt;&gt; expressionTree); </code></pre> <p>The latter will get passed a representation of the <a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree" rel="noreferrer">abstract syntax tree</a> that describes the expression <code>x &gt; 5</code>. LINQ to SQL relies on this behavior to be able to turn C# expressions in to the SQL expressions desired for filtering / ordering / etc. on the server side.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload