Saturday, September 28, 2013

Lambda Expressions : An Introduction


One definition of a lambda, λ, is the eleventh letter of the Greek alphabet and also has a value of 30 in the Greek numerical system. Another common usage is in fraternity and sororities. Wikipedia gives at least twenty different uses of the Lambda. Personally, the most awesome is the use of the lambda is in calculus with the second greatest use of the Lambda being in computer science. With the introduction of LINQ, lambda usage has not only soared in code usage but the context is also easier to understand.

Per MSDN, “A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls.” To learn more about delegates, go here.

In .NET, the most basic lambda expression can be recognized by its operator, “=>”, where input parameters are on the left side of the operator and either an expression or statement is on right side. For example, in the most basic expression below, a parameter, “x” is passed in and the returned result is the value of “x” squared:

EXAMPLE #1 – Basic Expression Lambda :

//Simple Expression Lambda:
delegate int del(int i);
public static void useDelegate()
{
    del d = x => x * x;
    int intParam = d(5);
    Console.WriteLine("intParam now has a value of {0}.", intParam);
    Console.ReadLine();
}

Result:



EXAMPLE #2 – Expression Lambda with multiple parameters:

//Expression Lambda returning a bool:
delegate bool del2(int i, string s);
public static void useTwoVariables()
{
    del2 d = (int x, string s) => s.Length > x;
    bool val = d(5, "ten");
    Console.WriteLine("The bool value of the expression is : {0}", val);
    Console.ReadLine();  
}

Result:



EXAMPLE #3 – Statement Lambda:

//Statement Lambda using strings to create a message
delegate void CreateMessage(string s);
public static void useStrings()
{
    CreateMessage cStr = x => { string s = x + " " + "is reigning MotoGP World Champion."Console.WriteLine(s); };
    cStr("Jorge Lorenzo, #99, ");
    Console.ReadLine();
}

Result:



EXAMPLE #3 – Using Lambda on Generics:
//Use the Query Operator func on generic delegates
public delegate TResult Func<TArg0, TResult>(TArg0 arg0);
public static void useFunc()
{
    int a = 15;
    Func<intint> func = x => x / x;
    Console.WriteLine("Result is {0}", func(a));
    Console.ReadLine();
}



Result:



No comments:

Post a Comment