Pages

Men

rh

7/01/2012

Lambda Expressions in C#

Lambda Expressions:
      A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
  •  All lambda expressions use the lambda operator =>, which is read as "goes to".
  • The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block.
  • The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type as follows:
Example:

      delegate int del(int i);
static void Main(string[] args)
{
    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
}
To create an expression tree type:
using System.Linq.Expressions;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression<del> myET = x => x * x;
        }
    }
}
 
A lambda expression with an expression on the right side is called an expression lambda. Expression lambdas are used extensively in the construction of Expression Trees 
               (input parameters) => expression
 
The parentheses are optional only if the lambda has one input parameter; otherwise they are required. Two or more input parameters are separated by commas enclosed in parentheses:
               (x, y) => x == y

Sometimes it is difficult or impossible for the compiler to infer the input types. When this occurs, you can specify the types explicitly as shown in the following example:
               (int x, string s) => s.Length > x

How to: Use Lambda Expressions in a Query

Example:
class SimpleLambda
{
    static void Main()
    {
 
        // Data source.
        int[] scores = { 90, 71, 82, 93, 75, 82 };
 
        // The call to Count forces iteration of the source
        int highScoreCount = scores.Where(n => n > 80).Count();
 
        Console.WriteLine ("{0} scores are greater than 80", highScoreCount);
 
        // Outputs: 4 scores are greater than 80            
    }
}
 
The above example demonstrates how to use a lambda expression in a method-based query by using the Enumerable. Where standard query operator. 
 
Note that the Where method in this example has an input parameter of the delegate type Func(Of TResult) and that delegate takes an integer as input and returns a Boolean. 
 
The lambda expression can be converted to that delegate

Expression Trees

Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.

Expression trees are also used in the dynamic language runtime (DLR) to provide interoperability between dynamic languages and the .NET Framework and to enable compiler writers to emit expression trees instead of Microsoft intermediate language (MSIL).

create an expression tree that represents the lambda expression num => num < 5 (C#)
 
Example:
 
Expression<Func<int, bool>> lambda = num => num < 5;

LINQ Query Expression:
  • Query expressions can be used to query and to transform data from any LINQ-enabled data source. For example, a single query can retrieve data from a SQL database, and produce an XML stream as output.
  • Query expressions are easy to master because they use many familiar C# language constructs.
  • The variables in a query expression are all strongly typed, although in many cases you do not have to provide the type explicitly because the compiler can infer it.
  • A query is not executed until you iterate over the query variable in a Foreach statement. For more information,
  • At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. Any query that can be expressed by using query syntax can also be expressed by using method syntax. However, in most cases query syntax is more readable and concise.
Examples:
class LINQQueryExpressions
{
    static void Main()
    {
 
        // Specify the data source.
        int[] scores = new int[] { 97, 92, 81, 60 };
 
        // Define the query expression.
        IEnumerable<int> scoreQuery =
            from score in scores
            where score > 80
            select score;
 
        // Execute the query.
        foreach (int i in scoreQuery)
        {
            Console.Write(i + " ");
        }            
    }
}
// Output: 97 92 81

No comments :

Post a Comment