LINQ - SPLessons

LINQ Lambda Expressions

Home > Lesson > Chapter 11
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

LINQ Lambda Expressions

LINQ Lambda Expressions

 

shape Introduction

This chapter demonstrates about the Lambda Expression which are used to apply the mathematical notations to the defining functions and LINQ transfer the logic to the expression at run time. The following are the concepts are covered in this chapter.
  • Lambda Expression
  • Lambda Type Inference

Lambda Expression

shape Description

Lambda Expression is derived from the lambda calculus these are applied to the defining functions. Lambda expression Translate the logic of the LINQ equations executable part at run time then which can pass the data source conveniently. A lambda expression acts as an anonymous function or method which returns "Single Value". A Lambda Expression, In generally will use the lambda operator represented by "=>". Syntax of the Lambda Expression is as shown below. [csharp] Input Parameter=>{Statements}; [/csharp] For Example If user write a statement like below a=>a*a; This a goes to a*a The code below demonstrate the Lambda expression is as shown below in c#. [csharp] using System.Collections.Generic; using System.Linq; using System.Text; namespace lambdaexample { class Program { delegate int del(int i); static void Main(string[] args) { del myDelegate = a => a * a; int j = myDelegate(5); Console.WriteLine(j); Console.ReadLine(); } } } [/csharp] Result Compiling and execute the above code in a Visual Studio then user will get the output is as shown below. The code below demonstrate the Lambda expression is as shown below in VB. [csharp] Module Module1 Private Delegate Function del(ByVal i As Integer) As Integer Sub Main(ByVal args As String()) Dim myDelegate As del = Function(a) a * a Dim j As Integer = myDelegate(5) Console.WriteLine(j) Console.ReadLine() End Sub End Module [/csharp] Result Compiling and execute the above code in a Visual Studio then user can get the output is a shown below.

Async Lambdas

shape Description

User can also create the asynchronous processing by using the async key word which is known as async lambdas the snippet below demonstrates the async lambda. [csharp] Func<Task<string>> getWordAsync = async() => “splessons”; [/csharp] Lambda Standard Query Operators Lambda Expression in a query operator is demonstrated by the requirements and which works on the each element in the sequence but not on whole sequence. user can give the own logic's by the lambda expression into the standard query operator. The code below demonstrates the using of Lambda expression by using "Where" operator in c#. [csharp] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace lambdaexample { class Program { static void Main(string[] args) { int[] fibNum = { 1, 2, 3, 5, 8, 13, 21, 34, 50 }; double averageValue = fibNum.Where(num => num % 2 == 1).Average(); Console.WriteLine(averageValue); Console.ReadLine(); } } } [/csharp] Result Compiling and execute the above code in a Visual Studio then user can get the output is a shown below. The code below demonstrates the using of Lambda expression by using "Where" operator in VB. [csharp] Module Module1 Sub Main() Dim fibNum As Integer() = {1, 2, 3, 5, 8, 13, 21, 34, 50} Dim averageValue As Double = fibNum.Where(Function(num) num Mod 2 = 1).Average() Console.WriteLine(averageValue) Console.ReadLine() End Sub End Module [/csharp] Result Compiling and execute the above code in a Visual Studio then user can get the output is a shown below.

Lambda Type Inference

shape Description

Type Inference is used in different types of situations which is not explicitly specified. In a lambda expression type inference will use only for the specified compiler. The snippet below demonstrates the type inference as shown. [csharp] delegate int Transformer (int i); [/csharp]

Expression Tree

shape Description

Expression Tree constructed with Lambda Expressions in a tree every node behave like a call or method. Statement Lambda Statement Lambda statements are not useful to construct the expression tree which consist two or three statements and the return value must be in lambda statement. The syntax of the statement lambda is as shown below [csharp] (params) => {statements} [/csharp] Variable Scope In order to use the variable scope user need to follow the some rules.
  • In the variable Scope captured variable is not collected by the garbage then delegate reference the eligible to the garbage collection.
  • In lambda expression user need to initiate the lambda expression if not which are not visible in outer method.
  • In order to get the enclosing method User need to prohibit the return statement in lambda expression.
The code below demonstrates the variable scope is as shown. [csharp] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace lambdaexample { class Program { delegate bool D(); delegate bool D2(int i); class Test { D del; D2 del2; public void TestMethod(int input) { int a = 0; // Initialize the delegates with lambda expressions. // Note access to 2 outer variables. // del will be invoked within this method. del = () => { a = 10; return a > input; }; // del2 will be invoked after TestMethod goes out of scope. del2 = (x) => { return x == a; }; // Demonstrate value of j: // The delegate has not been invoked yet. Console.WriteLine("a = {0}", a); // Invoke the delegate. bool boolResult = del(); Console.WriteLine("a = {0}. b = {1}", a, boolResult); } static void Main() { Test test = new Test(); test.TestMethod(5); // Prove that del2 still has a copy of // local variable a from TestMethod. bool result = test.del2(10); Console.WriteLine(result); Console.ReadKey(); } } } } [/csharp] Result Compiling and execute the above code in a Visual Studio then user can get the output is a shown below.

Summary

shape Points

  • Inference will work only on compiler specified type.
  • All nodes of expression tree behaves like a method or call.
  • Return statement of lambda statement must be a statement.